问题
If I dynamically allocate objects of a class inside a vector, is the destructor for each object called if I use clear()?
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/6326246/c-is-destructor-called-when-a-vector-holds-objects