I was experimenting with destructors in C++ with this piece of code:
#include
struct temp
{
~temp() { std::cout << \"Hello!\" <
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 ?
That's correct.
I must mention that im not intending to do this in practice. Im just trying to understand whats going on here.
You've called the destructor, preparing an object to be destroyed. But this is also done automatically when an object goes out of scope, before it's actually de-allocated.
The thing to understand is this: If you do things that don't make sense, then bad things happen. So don't do things that don't make sense. If you manually call a destructor, the descructor runs. That has no effect on anything else unless the destructor actually does something that has an effect.
You just call the destructor, you don't actually free any memory (it is statically allocated). If you use new and then delete the destructor will only be called once.
You don't call the destructor explicitly, it is called automatically when the variable goes out of scope (here after the return 0;
statement). That's why it is called twice, you call it, and then the system calls it.
If you want to be able to remove an instance of this class yourself, explicitly, you need to dynamically allocate it:
temp *t = new temp;
// do stuff with t...
delete t; // do not forget this, or the constructor is not being called at all
You shouldn't actually call the deconstructor. It is called for you by the runtime support. Hence your calling it once and the runtime support is calling it the second time.
Here is some food for thought on destructors:
http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fcplr380.htm
You can explicitly call deconstructors, however it's not recommended, normally they are implicitly called.