我有以下示例代码来解释我的问题。根据 STD 映射容器文档 ( http://www.cplusplus.com/reference/map/map/operator%5B%5D/ ),operator[](或“at”方法)返回对映射值的引用。我明白了第 13 行编译和工作正常的原因(当我将一个元素插入 vec1 时,map 中的映射值得到更新)。我不明白为什么第 13 行不会导致编译错误,因为 vec1 不是引用并且 operator[] 返回引用。
1 #include <map>
2 #include <vector>
3
4 using namespace std;
5
6 int main()
7 {
8 map<int, vector<int> > port;
9
10 port[1] = vector<int>(1, 10);
11
12 vector<int> &vec1 = port[1]; // <===
13 vector<int> vec2 = port[1]; // <===
14
15 return 0;
16 }
我想也许 operator[] 的实际实现被重载以返回两种类型(值和引用)。然而,当我查看“ map ”头文件时,它似乎没有(除非我遗漏了什么):
文件:/usr/include/c++/4.7/profile/map.h
// 23.3.1.2 element access:
mapped_type&
operator[](const key_type& __k)
{
__profcxx_map_to_unordered_map_find(this, size());
return _Base::operator[](__k);
}
#ifdef __GXX_EXPERIMENTAL_CXX0X__
mapped_type&
operator[](key_type&& __k)
{
__profcxx_map_to_unordered_map_find(this, size());
return _Base::operator[](std::move(__k));
}
#endif
有人能帮我理解一下吗?
最佳答案
类型通常可以从引用中复制构造。所以 vec2
只是 port[1]
返回的引用引用的值的拷贝。这是一个涉及 ints
的简单示例:
int i = 42;
int j& = i; // j is a reference to i
int k = j; // k is a copy of the int that j refers to, i.e. i.
关于你关于这两种返回类型的假设,你不能通过返回值重载函数。
关于c++ - map operator[] 的返回值(和 "at"方法),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19557857/