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.)
The signal emission most probably creates a copy of the object (using default copy constructor - so pointers in both object point to the same thing!), so the destructor is called twice, once for your filtmp and second time for the copy. Up to this point signal is not connected to anywhere.
Why is the destructor being called three times?
An explicit call to destructor is only necessary when an object is placed at a particular location in memory by using placement new. Destructor should not be called explicitly when the object is dynamically allocated because the delete operator automatically calls destructor.
A destructor is a member function that is invoked automatically when the object goes out of scope or is explicitly destroyed by a call to delete .
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.
Calling the destructor does not free the object.
The destructor is there to clean up the internals of the object and then the object itsself is freed after the destructor finishes.
It's an error to do what you are doing similarly to the way that you can call delete twice on an object but it's an error to do so.
There are only a very few cases where you want to call the destructor manually and this isn't one of them. It's really there for the times you manually construct an object at a memory location using placement new and then need to be able to destruct it without freeing the memory.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With