如果我有一个带有地图作为私有成员的类,例如
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_;
}
在我的 main 函数中,这两段代码之间会有区别吗?
Code1:
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;
}
Code2:
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;
}
在 Code2 中,我刚刚创建了一个新的地图变量来保存从 getPlatforms() 函数返回的地图。
无论如何,在我的真实代码中(我无法发布真实代码,但它直接对应于这个概念),第一种方式(Code1)会导致运行时错误,无法访问某个位置的内存。
第二种方法有效!
您能否启发我了解这两个不同代码片段之间发生的理论基础?