将映射从一个函数传递到另一个函数时,如何正确处理内存。
我有一个函数返回它生成的 map 。值对象是Class foo。
我在三个不同的位置打印foo,并且它们都给出不同的值。第一次,它给出了正确的值。第二和第三是垃圾。
我知道我必须在正确的位置制作Foo对象指针。
我想知道在哪里?
std::map<int,Foo*> function_that_returns_the_map(){
std::map<int,Foo*> myMap;
{
int v = 0;
Foo *b = new Foo();
// PRINTING FOO FIRST
std::cout<<""<<*b<<endl;
myMap.insert(std::pair<int,Foo*>(v,b))
}
// PRINTING FOO AGAIN
for(map<int,Foo*>::iterator it = myMap.begin();
it != myMap.end(); ++it)
{
std::cout << " " << *(it->second) << "\n";
}
return myMap;
}
std::map<int, Foo*> myMap;
myMap = function_that_returns_the_map();
//PRINTING FOO AGAIN.
std::map<int, Board*>::iterator it = myMap.begin();
for (it=myMap.begin(); it!=myMap.end(); ++it)
cout<<" "<<*(it->second)<<endl;
Click here看我的实际代码。
更新:Foo的成员变量未使用“new”运算符分配。因此,它们超出范围并在超出范围后具有垃圾值。
最佳答案
您的代码中有很多小错误(我认为只是错别字)。我已经修复了这些问题,并提供了Foo
类,它可以编译并正常运行,并在所有三个位置打印正确的值:
#include <iostream>
#include <map>
struct Foo
{
Foo() : someValue(5) {};
int someValue;
};
std::map<int,Foo*> function_that_returns_the_map()
{
std::map<int,Foo*> myMap;
{
int v = 0;
Foo *b = new Foo();
std::cout << (*b).someValue << std::endl; // PRINTING FOO FIRST
myMap.insert(std::pair<int,Foo*>(v,b));
}
// PRINTING FOO AGAIN
std::map<int, Foo*>::iterator it = myMap.begin();
for(it; it != myMap.end(); ++it)
{
std::cout << it->second->someValue << "\n";
}
return myMap;
}
int main()
{
std::map<int, Foo*> myMap;
myMap = function_that_returns_the_map();
//PRINTING FOO AGAIN.
std::map<int, Foo*>::iterator it = myMap.begin();
for (it; it!=myMap.end(); ++it)
std::cout << it->second->someValue << std::endl;
return 0;
}
Click here查看输出。
因此,问题必须出在您未在问题中提及的地方。为了能够进一步提供帮助,我们需要查看真实的代码。
关于c++ - 返回后std::map值丢失,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16005533/