ShrimpCrackers
ShrimpCrackers

Reputation: 4542

C++ - Is destructor called when a vector holds objects?

If I dynamically allocate objects of a class inside a vector, is the destructor for each object called if I use clear()?

Upvotes: 2

Views: 2104

Answers (2)

Walter Mundt
Walter Mundt

Reputation: 25271

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.

Upvotes: 6

paxdiablo
paxdiablo

Reputation: 881983

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 in a, invalidates all references, pointers, and iterators referring to the elements of a and may invalidate the past-the-end iterator.

Upvotes: 1

Related Questions