I'm getting a weird bug. My deconstructor is getting called whenever I create an object on the stack, and then use its "insert" function. The insert function does not delete anything. If I create the object on the heap and then call insert, the deconstructor is never called (which is what I want, obviously). This problem only occurs with my insert function. Other functions like empty () or size () do not provoke the same error.
I'm using Visual Studio 2012.
Where the problem occurs:
Map n;
n.insert(5, "5");
//Map deconstructor gets called unexpectedly
Where the problem does not occur
Map *n = new Map ();
n->insert (5, "5");
//Map deconstructor does not get called
code:
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;
}