Custom Destructor

I have a container that holds pointers to other objects. These other objects are created dynamically outside of the container. When the container dies, I want all the objects it holds to also destruct.

I was thinking of implementing the destructor for container so that it deletes all the pointers.

I'm not sure if implementing a destructor will mess up the default destructor instructions. That is, if I reimplement the default destructor to call the destructors of the objects it contains, will the container clean up its memory as it does int he default deconstructor?
Last edited on
If you have dynamically allocated objects in the container, then provide your own container custom destructor is a must. If the object within also have dynamically allocated object, then you must provide a custom destructor for those objects too.

This is the typical norm for such stuff so you can keep yourself less busy by disallowing dynamically allocated objects in your class and containers.

PS the last sentence is not to be treated seriously :)
There is not default destructor. Just destructor.

As @sohguanh stated you must delete the dynamically allocated objects yourself.

I guess it's inside your container that you keep track of all your objects, so if you happen to delete the pointer before object destruction you create memory leakage. There is no way to destruct those objects besides their pointer.
If you are using a current C++ compiler use std::unique_ptr<> if the only pointers to the objects are in the sequence container, and the sequence has no duplicates, std::shared_ptr<> otherwise.

1
2
std::vector< std::unique_ptr<my_class> > sequence ;
std::list< std::shared_ptr<my_class> > another_sequence ;

http://www.devx.com/cplus/10MinuteSolution/39071/1954
http://en.cppreference.com/w/cpp/memory/unique_ptr
http://en.cppreference.com/w/cpp/memory/shared_ptr


If you are using an older compiler, one option is to use the smart pointers from Boost:
http://www.boost.org/doc/libs/1_48_0/libs/smart_ptr/smart_ptr.htm



+1 for std::unique_ptr<> or Boost's smart pointer. It is the way to go and saves you from writing a destructor of your own (and of course, a container class of your own). Be very sure NOT to use std::auto_ptr. It cannot be used in STL containers.
Topic archived. No new replies allowed.