If I dynamically allocate objects of a class inside a vector, is the destructor for each object called if I use clear()?
2 Answers
What do you mean by "dynamically allocate" precisely? If you use a vector<foo>
then you are fine. If you are putting pointers in via vector<foo*>
then destructors will not get called, because the pointers don't have destructors per se.
Note, however, that in the vector<foo>
case, you may find your constructors and destructors called a lot more than you expect e.g. when the vector is resized, because the vector will use them when moving the objects in memory if it needs to. You can use a Boost shared_ptr
to get around that, though there is a small perf cost due to the reference-count bookkeeping.
My advice: use vector<foo>
if the objects are cheap to copy and destroy, and vector<shared_ptr<foo> >
if they're expensive or hard/impossible to copy. Never use vector<foo*>
unless you specifically want to avoid having the vector handle memory management, and only then be careful; it's rarely a good idea IMHO.

- 24,753
- 5
- 53
- 61
-
If you use move on a object in the container; the object in the container stays but shouldn't be destroyed. What happens then? – this Jun 05 '14 at 13:37
-
The original answer was written before std::move() was in common use. What will happen is that the object will still be destroyed. This is actually the case in general, IIRC -- objects are expected to track when they've been "moved-from" and make their destructors behave appropriately. The only tricky part is that nobody is supposed to look at the moved-from element's state until it is assigned a new value or destroyed. – Walter Mundt Jun 06 '14 at 19:40
Yes, they are all cleaned up properly.
From this link:
All the elements of the vector are dropped: their destructors are called, and then they are removed from the vector container, leaving the container with a size of 0.
The [sequence.reqmts]
section of the upcoming standard also makes this clear:
a.clear()
destroys all elements ina
, invalidates all references, pointers, and iterators referring to the elements ofa
and may invalidate the past-the-end iterator.

- 854,327
- 234
- 1,573
- 1,953