<分区>
我一直在从事 Qt 项目,但在删除 map 中保存的对象时遇到了问题。我准备了一个简单的 C++ 代码来展示我的问题:
#include <iostream>
#include <map>
#include <string>
using namespace std;
class A
{
public:
int *tab;
A()
{
tab = NULL;
}
~A()
{
if (tab != NULL)
{
delete[] tab;
}
}
};
int main()
{
map<string, A> mapa;
string name = "MyArray";
A *a = new A;
a->tab = new int[3];
a->tab[0] = 1;
a->tab[1] = 2;
a->tab[2] = 3;
mapa[name] = *a;
delete a;
system("PAUSE");
return 0;
}
关闭程序后我得到: 调试断言失败!
_BLOCK_TYPE_IS_VALID 等..
我的问题是:这是为什么?原因可能是 map 在我退出程序后被删除,并且它包含一个在我关闭程序之前被删除的 A 对象 (a)。但是,我传递的是一个值,而不是地址,这是什么问题?
这个值不是刚刚复制到映射中并保存在某个不同的地址中吗?