我有以下示例代码来解释我的问题.根据STD地图容器文档(http://www.cplusplus.com/reference/map/map/operator%5B%5D/),operator [](或"at"方法)返回对映射值的引用.我明白为什么第13行编译并正常工作(当我将元素插入vec1时,映射中的映射值会更新).我不明白为什么第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 }
Run Code Online (Sandbox Code Playgroud)
我想也许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
Run Code Online (Sandbox Code Playgroud)
有人可以帮我理解这个吗?
类型通常可以从引用中复制构造.所以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.
Run Code Online (Sandbox Code Playgroud)
关于关于两种返回类型的假设,您不能通过返回值重载函数.