jbgs
jbgs

Reputation: 2885

Custom destructor in STL container

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

Answers (3)

Mike Seymour
Mike Seymour

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:

  • 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.

Upvotes: 6

Alon
Alon

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

ForEveR
ForEveR

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

Related Questions