Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicitly calling a destructor using a pointer to an object

Not to use in any implementation but just for the sake of understanding I am trying to explicitly call a destructor using an object and another * to object.

CODE

#include<iostream>
using namespace std; 

class A{
public :
A(){
    cout<<"\nConstructor called ";
}

~A()
{
    cout<<"\nDestructor called ";
}
};

int main()
{
    A obj,*obj1;
    obj1->~A();
    obj.~A();
    return 0;
}


OUTPUT

output1


Now the problem is that I can't understand why destructor is called three times.
Even if the obj1 is not yet pointing to any object.
Note that I understand that the last two destructor calls are:

  1. because I am calling obj.~A();
  2. because we go out of the scope of object obj.

I am using DevC++ 5.5.1

like image 789
xor Avatar asked Oct 27 '25 09:10

xor


2 Answers

Your code only works by a fluke.

int main()
{   
    A obj,*obj1;
    obj1->~A(); // (1) Bad reference that works
    obj.~A();   // (2) Explicit call to destructor
    return 0;
} // (3) obj's destructor is called when obj goes out of scope
like image 77
user3344003 Avatar answered Oct 29 '25 22:10

user3344003


obj1->~A();

You dereference the pointer obj1 which has not been initialized. That is undefined behaviour.

In this situation, anything can happen and nothing is guaranteed.

like image 38
Daniel Daranas Avatar answered Oct 29 '25 23:10

Daniel Daranas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!