0

今天我才知道引用不可重新安装 考虑代码:

map<int,int> z;
z.insert(make_pair(1,2));
z.insert(make_pair(3,5));
z.insert(make_pair(4,6));
auto ref = z.at(1);
ref = z.at(3);

std::map::at返回对所请求元素的映射值的引用,暗示 ref 是一个引用。为什么允许重新分配(因为不能重新绑定引用)。这里发生了什么。

4

1 回答 1

2

auto不创建引用类型。表达式z.at(1)是类型的左值int,因此ref也是 int。

(如果你想要参考,你必须说auto &or auto &&(或在 C++14 中decltype(auto))。)

于 2013-07-16T23:30:05.693 回答