在下面的例子中,有谁知道为什么 const
被添加到给出下面错误的字符串中(与 gcc 和 VS2008 相同)?
#include<utility>
#include<ostream>
#include<string>
#include<map>
class Foo
{
};
class Test
{
public:
Test() { myMap.insert(std::make_pair("a string", Foo())); }
std::pair<std::string, Foo>& GetPair() { return *(myMap.begin()); }
private:
std::map<std::string, Foo> myMap;
};
int main()
{
Test t;
std::pair<std::string, Foo>& myPair = t.GetPair();
return 0;
}
错误:
t.cpp: In member function 'std::pair<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, Foo>& Test::GetPair()':
Line 14: error: invalid initialization of reference of type 'std::pair<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, Foo>&' from expression of type 'std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char> >, Foo>'
compilation terminated due to -Wfatal-errors.
我不明白为什么会这样,因为我没有使用 cbegin()
。另外,为什么字符串是 const
,而不是 Foo
?
最佳答案
因为如果您更改了对的关键部分,那么它会突然存储在 map 数据结构中的错误位置(存储桶、树中的位置或其他取决于结构的位置)。当关键部分发生变化时, map 不会收到通知,因此它根本不允许您修改它。
另一方面,值部分与该对在映射结构中的存储位置无关,因此您可以更改它。
关于c++ - 为什么将 const 添加到从迭代器中提取的这对字符串中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26639570/