我有以下示例代碼來解釋我的問題。根據STD地圖容器doc(http://www.cplusplus.com/reference/map/map/operator%5B%5D/),運算符[](或「at」方法)返回對映射值的引用。我明白了爲什麼第13行編譯並正確工作(當我將元素插入到vec1中時,映射中的映射值得到更新)。我不明白爲什麼第13行不會導致編譯錯誤,因爲vec1不是引用,運算符[]返回引用。返回值映射運算符[](和「在」方法)
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 }
我想也許是運算符[]的實際實現被重載以返回兩種類型(值和參考)。然而,當我通過「地圖」頭文件看,它似乎沒有(除非我失去了一些東西):
文件:/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
有人能幫我理解嗎?
但'vec1' *是一個參考。 – juanchopanza
對不起,我的意思是第13行,其中vec2不是參考。 (我糾正了我原來的問題)。 –