面向对象自杀或删除这个; [英] Object-Oriented Suicide or delete this;

查看:220
本文介绍了面向对象自杀或删除这个;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用MSVC9.0编译的以下代码运行并输出析构四次,这是合乎逻辑的。

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();
}



我认为main中的前四行代码不会导致未定义的行为(虽然不完全确定 delete this; 事)。我想要一个确认或<确认反义词的占位符> 。但我对第5行和第6行有严重的怀疑。允许显式调用析构函数,不是吗?但是,被认为是在那之后完成的对象的生命周期?也就是说,是在允许(定义)析构函数的显式调用之后调用另一个成员吗?

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)?

推荐答案


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

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

p-> CommitSuicide(); // line 6

p->CommitSuicide(); //line 6

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

这篇关于面向对象自杀或删除这个;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆