Today I was wondering about c++ destructors so I wrote a small test program. That answered my original question but raised a new one which is:
The following program:
#include "stdafx.h"
#include <vector>
#include <iostream>
using namespace std;
class test
{
public:
int id;
vector<test> collection;
test(){}
test(int id_in){id = id_in;}
~test(){cout << "dying: " << id << "\n";}
};
int _tmain(int argc, _TCHAR* argv[])
{
{
test obj(1);
obj.collection.push_back(test(2));
obj.collection.push_back(test(3));
cout << "before overwrite\n";
obj = test(4);
cout << "before scope exit\n";
}
int x;
cin >> x;
}
produces the following output:
dying: 2
dying: 2
dying: 3
before overwrite
dying: 2
dying: 3
dying: 4
before scope exit
dying: 4
Why don’t I see a destructor for my test object with id 1? If its destructor isn’t called when it is overwritten, than what calls the destructors of the instances in its vector?
You violate the Rule of Three by creating a destructor, but no assignment operator.
From reading that, you can interpret your code as follows:
When the line
is compiled, a temporary instance of
testis created with id 4.Then, the assignment operator is called. Since you did not provide one, the compiler generated one for you that looks like this:
The id 1 is simply overwritten with the 4 from the temporary, and for the collection assignment, the assignment operator of
std::vectoris called.std::vector‘s assignment operator deletes all previously contained elements, which is why you seein your output. Finally, the temporarily created obj instance with id 4 is deleted, causing
to appear for the first time. When
objgoes out of scope, you see theoutput once more.