Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destructor being called twice when being explicitly invoked

Tags:

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.)

like image 425
Cygnus Avatar asked Aug 09 '12 13:08

Cygnus


People also ask

Why is my destructor being called twice?

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.

How many times destructor is invoked?

Why is the destructor being called three times?

Is destructor called implicitly?

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.

Is destructor called automatically in C++?

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 .


2 Answers

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.

like image 99
Jonathan Grynspan Avatar answered Sep 28 '22 12:09

Jonathan Grynspan


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.

like image 26
jcoder Avatar answered Sep 28 '22 10:09

jcoder