c++ - 为什么将 const 添加到从迭代器中提取的这对字符串中?

标签 c++

在下面的例子中,有谁知道为什么 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/

相关文章:

c++ - 跨平台项目中的 Eigen 错误

c++ - const 指针作为 std::bind 参数

c++ - g++: const 丢弃限定符

c++ - boost::copy_graph 的vertex_copy 是如何工作的?

c++ - 如何为多个文件处理选择最佳 I/O 策略?

c++ - 注册管理技巧

c++ - 如何设计相互依赖的策略类实现

c++ - 长与。诠释 C/C++ - 有什么意义?

java - 自动化设计模式 C++

c++ - 有效地在 C++ 类之间传输数据