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