jmasterx
jmasterx

Reputation: 54133

Will destructor be called?

If I create a vector of vector of vector, if I clear the first vector, or the first vector gets deleted, will all the child vectors call the destructor and free the memory or will it cause a memory leak? Thanks

Upvotes: 1

Views: 264

Answers (4)

xtofl
xtofl

Reputation: 41519

The STL offers only value-semantics. This means that you shouldn't bother with memory allocation/deallocation issues as long as you don't put pointers into your containers. Objects are destructed when deleted from the container, so also when the container itself is destructed (or cleared).

This also means that many operations on those containers will involve (default) constucting, copying, and destructing objects.

Upvotes: 2

John
John

Reputation:

Yes. Destructor will be called and the memory will be freed.

Upvotes: 0

bshields
bshields

Reputation: 3593

There will only be a memory leak if you used new to create the contained vectors. Calling clear() on a vector will NOT call delete on the contained items.

Upvotes: 3

anon
anon

Reputation:

If you have:

vector <vector <vector <int> > > > v;
v.clear();

then destructors will be called suitably for all the subvectors.

Upvotes: 5

Related Questions