Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object-Oriented Suicide or delete this;

The following code compiled with MSVC9.0 runs and outputs Destructor four times, which is logical.

#include <iostream>
class SomeClass
{
public:
   void CommitSuicide()
   {
      delete this;
   }
   void Reincarnate()
   {
      this->~SomeClass();
      new (this) SomeClass;
   }
   ~SomeClass()
   {
      std::cout  << "Destructor\n";
   }
};

int main()
{
   SomeClass* p = new SomeClass;
   p->CommitSuicide();
   p =  new SomeClass;
   p->Reincarnate();
   p->~SomeClass(); //line 5
   p->CommitSuicide();
}

I think the first 4 lines of code in main do not result in undefined behavior (although not entirely sure about the delete this; thing). I would like to have a confirmation or < placeholder for confirmation's antonym > of that. But I have serious doubts about lines 5 and 6. It is allowed to explicitly call the destructor, isn't it? But is the lifetime of the object considered to have finished after that? That is, is invocation of another member after the explicit call of the destructor allowed (defined)?

To summarize, which parts of the above code (if any) result in undefined behavior (technically speaking)?

like image 430
Armen Tsirunyan Avatar asked Oct 18 '10 13:10

Armen Tsirunyan


2 Answers

The delete this; is fine. The last p->CommitSuicide(); gives undefined behavior because you already destroyed the object in "line 5".

like image 112
Jerry Coffin Avatar answered Sep 20 '22 13:09

Jerry Coffin


p->~SomeClass(); //line 5

p->CommitSuicide(); //line 6

Line (6) definitely invokes Undefined Behaviour.

That is, is invocation of another member after the explicit call of the destructor allowed (defined)?

No! Your assumption is correct.

like image 23
Prasoon Saurav Avatar answered Sep 20 '22 13:09

Prasoon Saurav