The folowing code shows an output not expected:
class test
{
public:
test()
{
std::cout << "Created" << (long)this << std::endl;
}
~test()
{
std::cout << "Destroyed" << (long)this << std::endl;
}
};
int main(int argc, char** argv)
{
std::vector<test> v;
test t;
v.push_back(t);
return EXIT_SUCCESS;
}
When executed it shows:
Created-1077942161
Destroyed-1077942161
Destroyed674242816
I think the second “Destroyed” output should not be there. When I don’t use the vector the result is one Created and one Destroyed line as expected. Is this behavior normal?
(This is compiled with GCC on a FreeBSD system)
Everything is as it should be: there’s the local variable
t, which gets created and then destroyed at the end ofmain(), and there’sv[0], which gets created and destroyed at the end ofmain().You don’t see the creation of
v[0]because that happens by copy or move constructor, which your test class doesn’t provide. (So the compiler provides one for you, but without output.)For testing purposes it’s handy to write for yourself once and for all a test class that contains all the possible constructors, destructors, assignment and swap operators and prints a diagnostic line in each, so you can witness how objects behave when used in containers and algorithms.