Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On calling destructor for an object, it is called two times? [duplicate]

Tags:

c++

destructor

On calling desctructor explicitly, it is executed two times. What's the reason for that?

#include <iostream>
using namespace std;

class A
{
    public:
        int x;

        A() { cout << "A's constructor called " << endl;  }

        ~A(){
            cout<<"A's desctructor called "<<endl;
        }
};

int main()
{
    A a;
    A b;
    a.~A();
}

Output:

A's constructor called
A's desctructor called
A's desctructor called

like image 434
user3747190 Avatar asked Dec 05 '22 23:12

user3747190


2 Answers

Well, you called it for 'a', and then 'the language' called it again for 'a' when the object went out of scope. And then, of course, 'the language' called it for b. By 'the language', I mean, of course, the very basic rule that automatic-scope objects are constructed as their scope initialize, and destructed when their scope ends.

Using explicit calls to destructors is rarely a good idea.

like image 87
bmargulies Avatar answered Dec 28 '22 22:12

bmargulies


You shouldn't call the destructor by hand, it will get called automatically when the object goes out of scope.

The only place to manually call destructors is when you're writing your own allocator, but that is quite an advanced topic, so the rule of thumb would be to never call the destructor by hand.

like image 29
Jakub Arnold Avatar answered Dec 28 '22 22:12

Jakub Arnold