mousey
mousey

Reputation: 11901

Question regarding C++ Lists

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.

Upvotes: 0

Views: 198

Answers (7)

fredoverflow
fredoverflow

Reputation: 263128

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

Upvotes: 2

R Samuel Klatchko
R Samuel Klatchko

Reputation: 76541

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

Upvotes: 1

Thomas
Thomas

Reputation: 181745

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.

Upvotes: 2

Naveen
Naveen

Reputation: 73443

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.

Upvotes: 0

codaddict
codaddict

Reputation: 455030

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

Upvotes: 0

piotr
piotr

Reputation: 5787

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

Upvotes: 0

jweyrich
jweyrich

Reputation: 32240

No. You still have to deallocate it.

Upvotes: 0

Related Questions