2

In the following code the destructor for a is called twice, and the first call seems to be ignored:

struct A1
{
    int A;
    A1(int a=0) : A(a) { std::cout << "ctor: " << A << "\n"; std::cout.flush(); }
    ~A1() { std::cout << "dtor: " << A << "\n"; std::cout.flush(); }
};


int main()
{
    A1 a(1), *pa=new A1(2), *pb=new A1(3);

    a.~A1();
    pa->~A1();
    delete pb;
    std::cout << "'destructed' a.A = " << a.A << "\n"; std::cout.flush();

    return 0;
}

Output:

ctor: 1
ctor: 2
ctor: 3
dtor: 1
dtor: 2
dtor: 3
'destructed' a.A = 1
dtor: 1

What is happening here?

dragosht
  • 3,237
  • 2
  • 23
  • 32
slashmais
  • 7,069
  • 9
  • 54
  • 80
  • 5
    You have undefined behaviour. When `a` goes out of scope, its destructor is called. Also, you print `a.A` when `a` is in a desroyed state. – chris Jul 25 '14 at 18:11
  • @40two: thx for the link - I used wrong search terms & didn't find it myself. – slashmais Jul 25 '14 at 18:18

1 Answers1

10

Unless you really know what you are doing, you should never directly call the destructor of an object. Instead, allow the destructor to be called when you delete an object (that was allocated with new) or when it goes out of scope.

In your case a.~A1(); will lead to undefined behavior, because you'll call the destructor again when a goes out of scope.

Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
  • Thx for the answer but the link provided by 40two above shows that this question is a dupe & I'll ask for it to be deleted - sorry for your loss of rep ... – slashmais Jul 25 '14 at 18:28
  • @slashmais: No worries. Internet points are not that important. – Bill Lynch Jul 25 '14 at 18:29
  • @slashmais don't delete the question. The fact that is a duplicate doesn't matter, maybe some future reader will find your question more suitable than the one I posted :). – 101010 Jul 25 '14 at 18:40