0

list 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.

R Samuel Klatchko
  • 74,869
  • 16
  • 134
  • 187
mousey
  • 11,601
  • 16
  • 52
  • 59

7 Answers7

2

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
  • 174,939
  • 50
  • 355
  • 478
  • So If I call list 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 May 07 '10 at 06:04
  • @mousey If the 2 containers hold the same type, yes. – jweyrich May 07 '10 at 06:15
2

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

fredoverflow
  • 256,549
  • 94
  • 388
  • 662
1

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
  • 74,869
  • 16
  • 134
  • 187
0

No. You still have to deallocate it.

jweyrich
  • 31,198
  • 5
  • 66
  • 97
0

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

piotr
  • 5,657
  • 1
  • 35
  • 60
0

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

codaddict
  • 445,704
  • 82
  • 492
  • 529
0

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
  • 74,600
  • 47
  • 176
  • 233
  • I didnt get you Naveen so If I call list dog2; dog2.push_back(dog.front()); and then I will call dog.pop_front() So this will work? – mousey May 07 '10 at 06:03
  • @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 May 07 '10 at 06:06