2014-10-06 99 views
0

我收到一个奇怪的错误。每当我在堆栈中创建一个对象时,我的解构器就会被调用,然后使用它的“插入”功能。插入功能不会删除任何内容。如果我在堆上创建对象然后调用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; 
} 
+1

'n'是否超出范围?你应该整理一个你正在做的事情的简短例子。 – 2014-10-06 05:04:14

+2

你需要先学习语言。对于这个问题,学习内存管理部分 – 2014-10-06 05:04:21

+0

你能提供[一个我们可以实际运行的例子](http://stackoverflow.com/help/mcve)吗?您发布的内容缺少我们需要查看的问题来回答问题。 – user2357112 2014-10-06 05:04:53

回答

0

哎呀,我刚刚意识到,这实际上预计。在我的主函数(实例化和插入对象的位置)退出后,解构器自动调用。当在堆上创建对象时,不会发生这种情况,除非我明确地调用delete。 它仅在插入期间发生,因为在解构对象之前检查根是否不为NULL。如果没有插入,则根为NULL,并且函数刚刚退出。

非常感谢。

1

这是析构函数如何工作在C++

自动对象的析构函数都会被自动调用。动态分配的对象需要你delete他们。