2

We know that destructors are called automatically when the (non static) objects runs out of the declaration scope. But what if we invoke destructor explicitly?

So I have this code:

class A
{
public:
     A(){std::cout<<"A's ctor"<<std::endl;}
     ~A(){std::cout<<"A's dtor"<<std::endl;}
};

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

And it outputs:

A's ctor
A's dtor
A's dtor

Does this mean that the object is destructed twice?

anatolyg
  • 26,506
  • 9
  • 60
  • 134
Eduard Rostomyan
  • 7,050
  • 2
  • 37
  • 76
  • 9
    its almost never right to explicitly invoke destructors. What you have here is _undefined behavoir_ as there's no mechanism in C++ which 'remembers' you've invoked a destructor and doesn't invoke it a second time. Dont do that. – Mike Vine Mar 06 '18 at 11:47
  • 3
    What is the *real* problem you want to solve? *Why* do you want to manually call the destructor? – Some programmer dude Mar 06 '18 at 11:47
  • 1
    Not a problem but trying to understand the behavior. @MikeVine 's comment has everything sorted. – Eduard Rostomyan Mar 06 '18 at 11:49
  • 1
    @MikeVine - Why post an answer in the comment section? I couldn't find a decent duplicate. – StoryTeller - Unslander Monica Mar 06 '18 at 11:50
  • See also [here](https://stackoverflow.com/q/4580969/509868) – anatolyg Mar 06 '18 at 11:51
  • Be aware that the second call is undefined behaviour as you are invoking a function on an object (semantically) not existing any more at that time! – Aconcagua Mar 06 '18 at 11:53
  • 4
    Side note: One of the very rare occasions you need to call the destructor explicitly is when you create instances via placement new... – Aconcagua Mar 06 '18 at 11:54
  • Related: https://stackoverflow.com/questions/14187006/is-calling-destructor-manually-always-a-sign-of-bad-design – UKMonkey Mar 06 '18 at 12:15
  • @StoryTeller: Answering in the comments is in vogue for some reason. Some people even brag about it! Crazy. FWIW, answers do not go in comments, not normally and _especially_ not when there is a dupe or some other reason to close the question. Quoting SE community manager Robert Cartaino, "that is the worst of both worlds." – Lightness Races in Orbit Mar 06 '18 at 13:01

0 Answers0