Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to destroy a vector of pointers in c++?

Tags:

c++

I have the following code in one of my methods:

vector<Base*> units;
Base *a = new A();
Base *b = new B();
units.push_back(a);
units.push_back(b);

Should I destroy the a and b pointers before I exit the method? Or should I somehow just destroy the units vector of pointers?

Edit 1:

This is another interesting case:

vector<Base*> units;
A a;
B b;        
units.push_back(&a);
units.push_back(&b);

What about this case? Now I don't have to use delete nor smart pointers.

Thanks

like image 985
user2381422 Avatar asked May 29 '13 07:05

user2381422


People also ask

Do I need to delete a vector of pointers?

Solution. Store pointers to your objects in a vector instead of copies of the objects themselves. But if you do, don't forget to delete the objects that are pointed to, because the vector won't do it for you. Example 6-4 shows how to declare and work with vector s of pointers.

Does deleting a vector delete its contents?

Yes, the vector 's destructor will be called, and this will clear its contents.


3 Answers

If you exit the method, units will be destroyed automatically. But not a and b. Those you need to destroy explicitly.

Alternatively, you could use std::shared_ptr to do it for you, if you have C++11.

std::vector<std::shared_ptr<Base>> units;

And you just use the vector almost as you did before, but without worrying about memory leaks when the function exists. I say almost, because you'll need to use std::make_shared to assign into the vector.

like image 79
StoryTeller - Unslander Monica Avatar answered Sep 30 '22 20:09

StoryTeller - Unslander Monica


A rather old-fashioned solution, that works with all compilers:

for ( vector<Base*>::iterator i = units.begin(); i != units.end(); ++i )
    delete *i;

In C++11 this becomes as simple as:

for ( auto p : units )
    delete p;

Your second example doesn't require pointer deallocation; actually it would be a bad error to do it. However it does require care in ensuring that a and b remain valid at least as long as units does. For this reason I would advise against that approach.

like image 38
Nicola Musatti Avatar answered Sep 30 '22 19:09

Nicola Musatti


You need to iterate over the vector and delete each pointer it contains. Deleting the vector will result in memory leaks, as the objects pointed to by its elements are not deleted.

TL;DR: The objects remain, the pointers are lost == memory leak.

like image 45
Marc Claesen Avatar answered Sep 30 '22 21:09

Marc Claesen