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?
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With