Object-Oriented Suicide or delete this;

后端 未结 3 1657
闹比i
闹比i 2020-12-10 05:06

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

#include 
class SomeClass         


        
相关标签:
3条回答
  • 2020-12-10 05:28

    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.

    0 讨论(0)
  • 2020-12-10 05:39

    "delete this" is ok as long as you do not attempt to call any code of that object after the deletion (not even the destructor). So a self deleting object shoud only be placed at the heap and shoud have a private destructor to protect from creation on the stack.

    I dont know if a direct call to the destructor leads to undefined behaviour but a userdefined delete-operator would'nt get executed.

    0 讨论(0)
  • 2020-12-10 05:42

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

    0 讨论(0)
提交回复
热议问题