I was experimenting with destructors in C++ with this piece of code:
#include
struct temp
{
~temp() { std::cout << \"Hello!\" <
The destructor of a class could be invoked:
Explicitly
When the destructor is explicitly invoked using the object of the class, the same way you invoke another member function of the class.
Implicitly
When the object of the class goes out of scope or an object which is created using the new operator is destroyed using the delete operator.
In your sample program, you do both
int main()
{
temp t;
t.~temp(); //1. Calling destructor explictly using the object `t`
return 0;
} // 2. object `t` goes out of scope. So destructor invoked implictly
and that is the reason why you see the destructor being called twice.
As you have aptly thought, the destructor will destroy the resources which were created by constructor. So the destrutor should not be called explicitly, as it will result in destroying the already destroyed resource and that could be fatal.