tags:

views:

113

answers:

7

Hi,

list<Dog*> dog;
   .............
   ............

So I added many dog objects to it. If I call dog.pop_front();

Does memory automatically gets deallocated ? For the object that I popped out ?

So If I call

list<Dog*> dog2;
dog2.push_back(dog.front());

and then I will call dog.pop_front() So this will work? I will assume Dog as type struct.

A: 

No. You still have to deallocate it.

jweyrich
A: 

No, you have to deallocate it yourself by calling delete, or free, depending how you allocated it.

piotr
A: 

No. The memory for Dog object does not get deallocated. You'll have to make use of the delete operator to deallocate it.

codaddict
A: 

When you insert a Dog* into the list a copy of the pointer is created and insrted into the list. When you pop from the list memory allocated to this pointer is released. The memory allocated for the Dog object is not released as it was not allocated by the list. You have to release it yourself.

Naveen
I didnt get you Naveenso If I call list<Dog*> dog2;dog2.push_back(dog.front());and then I will call dog.pop_front()So this will work?
mousey
@mousey: Yes that will work. Important thing to note here is the *copy* of the pointer is inserted into the list. When you do pop this copy is deleted.
Naveen
+3  A: 

The memory for the Dog object does not get deleted; this you'll have to do yourself.

However, the memory for the pointer, of type Dog*, as well as any "list node" object wrapped around it, will be automatically deleted by the list class.

Thomas
So If I call list<Dog*> dog2; dog2.push_back(dog.front()); and then I will call dog.pop_front() So this will work? I will assume Dog as type struct.
mousey
@mousey If the 2 containers hold the same type, yes.
jweyrich
+1  A: 

You keep asking about this sequence:

list<Dog*> dog2;
dog2.push_back(dog.front());  // time 1
dog.pop_front();              // time 2

At time1, both dog2 and dog have a pointer to the same object.

At time2, the pointer to that object is removed from dog and is only in dog2.

Assuming you originally created that object with new Dog, the object will not be freed until you explicitly free it by calling delete ptr

R Samuel Klatchko
+2  A: 

I suggest a list<shared_ptr<Dog> > which takes care of deleting the dogs.

FredOverflow