Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom destructor in STL container

Tags:

c++

stl

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?

like image 333
jbgs Avatar asked Jan 24 '26 21:01

jbgs


1 Answers

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:

  • A destructor to delete each stored pointer;
  • A copy constructor and copy-assignment operator, either deleted, or perfoming a "deep" copy; otherwise, there's a danger of two vectors thinking they own the same objects;
  • Accessors to read and modify elements in such a way that you can't overwrite a stored pointer without deleting its object.
like image 183
Mike Seymour Avatar answered Jan 27 '26 11:01

Mike Seymour



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!