Suppose I have a class similar to the following:
#include <vector>
class element
{
public:
element();
~element();
virtual void my_func();
private:
std::vector<element*> _elements;
};
How would I go about implementing the destructor?
I was thinking something like this, but I’m not sure. I am worried about memory leaks since I’m relatively new to C++.
void element::destroy()
{
for(int i = 0; i < _elements.size(); ++i)
_elements.at(i)->destroy();
if(this != NULL)
delete this;
}
element::~element()
{
destroy();
}
Thank you.
PS:
Here is a sample main:
int main()
{
element* el_1 = new element();
element* el_2 = new element();
element* el_3 = new element();
el_1.add_element(el_2);
el_2.add_element(el_3);
return 0;
}
Also, what if I do this (aka don’t use new):
int main()
{
element el_1;
element el_2;
element el_3;
el_1.add_element(&el_2);
el_2.add_element(&el_3);
return 0;
}
delete thisin a destructor is always wrong:thisis already being destroyed!In addition, you would need to declare a copy constructor and copy assignment operator (either leaving them undefined, making your class noncopyable, or providing a suitable definition that copies the tree).
Alternatively (and preferably), you should use a container of smart pointers for
_elements. E.g.,When an
elementis destroyed, its_elementscontainer will be automatically destroyed. When the container is destroyed, it will destroy each of its elements. Astd::unique_ptrowns the object to which it points, and when thestd::unique_ptris destroyed, it will destroy the element to which it points.By using
std::vector<std::unique_ptr<element>>here, you don’t need to provide your own destructor, because all of this built-in functionality takes care of the cleanup for you.If you want to be able to copy an
elementtree, you’ll still need to provide your own copy constructor and copy assignment operator that clone the tree. However, if you don’t need the tree to be copyable, you don’t need to declare the copy operations like you do if you manage the memory yourself: thestd::unique_ptrcontainer is itself not copyable, so its presence as a member variable will suppress the implicitly generated copy operations.