#include <map>
#include <type_traits>
double foo(int key) {
const std::map a = {
std::pair<int, double>{1, .1},
std::pair<int, double>{2, .2},
};
static_assert(std::is_same_v<decltype(a)::value_type, std::pair<const int, double>>);
for (const std::pair<int, double> &i : a) {
if (i.first == key) {
return i.second;
}
}
return .0;
}
这里的for
循环中,每次循环都会产生map
中对应值的拷贝,因为map
中的值类型是std::pair<const int, double>
,而不是std::pair<int, double>
C++ Insights中对应的语句如下
for(; __begin1.operator!=(__end1); __begin1.operator++()) {
const std::pair<int, double> & i = std::pair<int, double>(__begin1.operator*());
if(i.first == key) {
return i.second;
}
}
确实生成了多余的拷贝
如果把for
循环中的类型改成std::pair<const int, double>
,或者直接用auto
的话,C++ Insights就变成了
for(; __begin1.operator!=(__end1); __begin1.operator++()){
const std::pair<const int, double> & i = __begin1.operator*();
if(i.first == key) {
return i.second;
}
}
成了引用,避免了无谓的性能损失