I was experimenting with destructors in C++ with this piece of code:
#include <iostream>
struct temp
{
~temp() { std::cout << "Hello!" << std::endl; }
};
int main()
{
temp t;
t.~temp();
}
I see that “Hello!” is being printed twice. Shouldn’t the calling of the destructor free the object and the destructor shouldn’t be called again when it goes out of scope? Or is there some other concept?
(I do not intend to do this in practice. I’m just trying to understand what’s going on here.)
It happens because you told it to happen. The destructor for an automatic variable is always called when the variable goes out of scope. You also called it. That’s two calls total.
Calling an object’s destructor does not signal to C++ not to call it again, since in normal execution there is no need to keep track.
The solution is to never manually call your destructor.