tags:

views:

105

answers:

4

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

+5  A: 

If you have:

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

then destructors will be called suitably for all the subvectors.

anon
Thanks!........
Milo
+3  A: 

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.

bshields
yea I understand that heap memory behaves different, thanks
Milo
A: 

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

+2  A: 

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.

xtofl