关于地图和迭代器的理论澄清

non*_*ble 3 c++ dictionary iterator

如果我有一个带有地图的类作为私人成员,例如

class MyClass
{
  public:
    MyClass();
    std::map<std::string, std::string> getPlatforms() const;
  private:
    std::map<std::string, std::string> platforms_;
};

MyClass::MyClass()
        :
{
  platforms_["key1"] = "value1";
  // ...
  platforms_["keyN"] = "valueN";
}

std::map<std::string, std::string> getPlatforms() const
{
  return platforms_;
}
Run Code Online (Sandbox Code Playgroud)

在我的主要功能中,这两段代码会有区别吗?

代码1:

MyClass myclass();
std::map<std::string, std::string>::iterator definition;
for (definition = myclass.getPlatforms().begin();
     definition != myclass.getPlatforms().end();
     ++definition){
  std::cout << (*definition).first << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

代码2:

MyClass myclass();
std::map<std::string, std::string> platforms = myclass.getPlatforms();
std::map<std::string, std::string>::iterator definition;
for (definition = platforms.begin();
     definition != platforms.end();
     ++definition){
  std::cout << (*definition).first << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

在Code2中,我刚刚创建了一个新的map变量来保存从getPlatforms()函数返回的映射.

无论如何,在我的真实代码中(我无法发布实际代码,但它直接对应于此概念)第一种方式(Code1)导致运行时错误,无法访问某个位置的内存.

第二种方式有效!

你能否告诉我这两个不同代码之间发生的事情的理论基础?

JSF*_*JSF 7

getPlatforms() 按值返回地图,而不是引用,这通常是一个坏主意.

你已经展示了一个为什么这是一个坏主意的例子:

getPlatforms().begin()是迭代器在使用迭代器之前消失的迭代器,是与getPlatforms().end()同一原始映射不同的副本上的迭代器.