s123
s123

Reputation: 471

Object on stack unexpectedly gets deleted

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;
}

Upvotes: 0

Views: 121

Answers (2)

mrjoltcola
mrjoltcola

Reputation: 20842

This is how destructors work in C++

Automatic objects' destructors are called automatically. Dynamically allocated objects require you to delete them.

Upvotes: 1

s123
s123

Reputation: 471

Whoops, I just realized that this actually is expected. After my main function (where the object is being instantiated and inserted into) exits, the deconstructor gets called automatically. This does not happen when object is created on the heap, unless I explicitly call delete. It happened only during insert because of a function that checks if the root is not NULL before going through with deconstructing the object. If there is no insert, the root is NULL, and function just exits.

Thanks a lot.

Upvotes: 0

Related Questions