堆栈上的对象意外删除

时间:2014-10-06 05:00:44

标签: c++

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

2 个答案:

答案 0 :(得分:1)

这就是析构函数在C ++中的工作方式

自动调用自动对象的析构函数。动态分配的对象要求您delete

答案 1 :(得分:0)

哎呀,我刚才意识到这实际上的预期。在我的main函数(对象被实例化并插入其中)退出之后,解构器会自动被调用。除非我显式调用delete,否则在堆上创建对象时不会发生这种情况。 它仅在插入期间发生,因为在执行解构对象之前,检查根是否为NULL的函数。如果没有插入,则root为NULL,函数退出。

非常感谢。