Reputation: 2885
Let's say I have a STL vector whose elements are raw pointers to other classes. It's obvious that the destructor of the vector won't release the memory owned by these pointers. Is it possible to implement a custom destructor that releases this memory?
Upvotes: 2
Views: 2056
Reputation: 254771
In modern C++, use vector<unique_ptr<T>>
, and all the ownership issues are managed for you.
If C++11 isn't available, you could use shared_ptr
(from Boost or TR1) rather than unique_ptr
, or you could use Boost's pointer containers. (Don't try to use the deprecated auto_ptr
, since that makes it far too easy to accidentally remove a pointer from the container. Presumably, the first comment is referring to this, but confusing it with the much safer unique_ptr
.)
If for some reason you can't use these, or if you really want to do the work yourself, you'll need to wrap the vector in a class with:
Upvotes: 6
Reputation: 1804
You need to iterate through the vector upon deletion and call the destructor of each element inside it
Or I guess the best option would be, instead of saving A*, save shared_ptr<A>
and then when no one no longer points to A, it will be destructed
Upvotes: 0
Reputation: 55897
No. You should clear elements manually, before destruction of vector. Something like
std::for_each(v.begin(), v.end(), [](const T* p) { delete p; });
or you can use something like boost::ptr_vector
(or some smart_pointers), that handle this case.
Upvotes: 3