std::unordered_map::at 作为左值如何工作?

How does std::unordered_map::at work as an lvalue?

据我所知,函数输出通常是右值。如 http://www.cplusplus.com/reference/unordered_map/unordered_map/at/ 的示例所示,我们可以使用如下赋值映射值:

mymap.at("Mars") = 3396;

这样的东西是如何工作的?

at() return引用地图中的值。这在您链接到的页面上也有说明:

mapped_type& at ( const key_type& k );  
const mapped_type& at ( const key_type& k ) const;

Returns a reference to the mapped value of the element with key k in the unordered_map.

看return类型。 & 表示 reference.

为引用赋值会将值赋给被引用的事物。例如:

int i = 0;
int &r = i;
r = 3396;

r 赋值更新 i

UPDATE:如评论中所述,at()const 和非 const unordered_map 对象重载。因此,mymap.at("Mars") = 3396; 只有在 mymap 不是 const 时才有效,因为 return 值是对非 const mapped_type 的引用] 因此是可写的。但如果 mymapconst,它将无法编译,因为 return 值将是对 const mapped_type 的引用,因此是只读的。例如:

const int i = 0;
const int &r = i;
r = 3396; // ERROR