I am confused about how to use destructors when I have a std::vector of my class.
So if I create a simple class as follows:
class Test
{
private:
int *big;
public:
Test ()
{
big = new int[10000];
}
~Test ()
{
delete [] big;
}
};
Then in my main function I do the following:
Test tObj = Test();
vector<Test> tVec;
tVec.push_back(tObj);
I get a runtime crash in the destructor of Test when I go out of scope. Why is this and how can I safely free my memory?
Your problem is here:
The
Test()creates a temporaryTestobject, which then gets copied totObj. At this point, bothtObjand the temporary object havebigset to point to the array. Then the temporary object gets destroyed, which calls the destructor and destroys the array. So whentObjgets destroyed, it tries to destroy the already-destroyed array again.Further, when
tVecis destroyed, it will destroy its elements, so the already-destroyed array will be destroyed yet again.You should define a copy constructor and an assignment operator so that when a
Testobject gets copied, thebigarray gets copied, or has some sort of reference count so that it doesn’t get destroyed until all owners are destroyed.An easy fix is to define your class like this:
In this case, you wouldn’t need to define any destructor, copy constructor, or assignment operator, because the
std::vector<>member will take care of everything. (But note that this means 10,000 integers get allocated and copied whenever you copy an instance ofTest.)