下面的代码片段编译时带有一个非常重要的警告。绑定const std :: pair <T, U>&std :: pair的值<const T, U>
#include <map>
#include <vector>
template <typename iterator>
const std::pair<int, float> &foo(iterator it) {
return *it;
}
int main() {
std::vector<std::pair<int, float>> vector;
std::map<int, float> map;
vector.push_back(std::make_pair(0, 0.0));
map.insert(std::make_pair(0, 0.0));
const std::pair<int, float> &r1 = foo(vector.begin());
const std::pair<int, float> &r2 = foo(map.begin());
if (r1 != r2) {
return 1;
}
return 0;
}
有从std::pair<const int, float>
到std::pair<int, float>
期间foo(map.begin())
创建的悬空参考的隐式转换。
ref2.cpp: In instantiation of ‘const std::pair<int, float>& foo(iterator) [with iterator = std::_Rb_tree_iterator<std::pair<const int, float> >]’:
ref2.cpp:16:52: required from here
ref2.cpp:7:11: warning: returning reference to temporary [-Wreturn-local-addr]
return *it;
^~
我们可以在这种情况下,调整的r2
类型std::pair<const int, float>
。尽管如此,在一般情况下,将两个调用的结果分配给类型兼容引用foo()
会很有用。例如,对foo()
的调用可能会封装在总是返回std::pair<int, float>&
的另一个函数中。
是否可以对参考分配进行操作,以解决const修饰符未对齐的问题?
你应该写'0.0f',所以你不会转换'双'到一个'浮动'(或者将你的'浮动'换成'双')。 –
为什么不使用'auto'? –
@KerrekSB函数返回引用是该规则的一个很大的例外。 – hvd