【发布时间】:2014-11-30 08:38:03
【问题描述】:
我遇到了一个奇怪的错误。每当我在堆栈上创建一个对象时,都会调用我的解构器,然后使用它的“插入”函数。插入函数不会删除任何内容。如果我在堆上创建对象然后调用插入,则永远不会调用解构函数(这显然是我想要的)。这个问题只发生在我的插入函数中。 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是否超出范围?您应该整理一个简短的完整示例来说明您正在做什么。 -
你需要先学习语言。对于这个问题,学习内存管理部分
-
你能提供an example we can actually run吗?您发布的内容缺少我们需要查看以回答问题的上下文。
-
如果您不致电
insert会怎样?您如何确定insert与您的问题有关? -
插入后是否有
}?
标签: c++