我得了一只奇怪的虫子。每当我在堆栈上创建对象时,我的解构函数就会被调用,然后使用它的“插入”函数。insert函数不删除任何内容。如果我在堆上创建对象,然后调用insert,解构函数就不会被调用(这显然是我想要的)。此问题仅在我的插入函数中发生。其他函数(如空()或size () )不会引发相同的错误。
我正在使用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;
}发布于 2014-10-06 05:27:41
这就是析构函数在C++中的工作方式。
自动对象的析构函数被自动调用。动态分配的对象要求您对它们进行delete。
发布于 2014-10-06 05:24:10
喔,我刚刚意识到这是预料之中的事。当我的主函数(其中的对象被实例化并插入到其中)退出后,解构函数将自动被调用。除非我显式地调用delete,否则在堆上创建对象时不会发生这种情况。它只在insert期间发生,因为一个函数在解构对象之前检查根根是否为空。如果没有insert,根目录为NULL,函数就退出。
非常感谢。
https://stackoverflow.com/questions/26210250
复制相似问题