我收到一个奇怪的错误。每当我在堆栈中创建一个对象时,我的解构器就会被调用,然后使用它的“插入”功能。插入功能不会删除任何内容。如果我在堆上创建对象然后调用insert,那么解构器永远不会被调用(显然,这正是我想要的)。这个问题只发生在我的插入功能。其他函数如empty()或size()不会引发相同的错误。堆栈上的对象意外删除
我使用Visual Studio 2012
发生问题:
Map n;
n.insert(5, "5");
//Map deconstructor gets called unexpectedly
在不出现
Map *n = new Map();
n->insert (5, "5");
//Map deconstructor does not get called
代码的问题:
struct node
{
int key;
string value;
node *left, *right;
};
//Note: I took away unrelated code from this function, b/c I narrowed down the problem
void Map::insert (int key, string value)
{
root = new node(); /**<-- This is the offending piece of code I think. If I comment it out, then the map deconstructor won't get called after the function exits*/
root->key = key;
root->value = value;
root->left = NULL;
root->right = NULL;
}
Map::~Map(void)
{
cout << "Deconstructor being called";
}
Map::Map(void)
{
root = NULL;
}
'n'是否超出范围?你应该整理一个你正在做的事情的简短例子。 – 2014-10-06 05:04:14
你需要先学习语言。对于这个问题,学习内存管理部分 – 2014-10-06 05:04:21
你能提供[一个我们可以实际运行的例子](http://stackoverflow.com/help/mcve)吗?您发布的内容缺少我们需要查看的问题来回答问题。 – user2357112 2014-10-06 05:04:53