c – 面向对象的自杀或删除此;
作者:互联网
以下使用MSVC9.0编译的代码运行并输出Destructor四次,这是合乎逻辑的.
#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中的前4行代码不会导致未定义的行为(虽然不完全确定删除这个;事情).我想要一个确认或<占位符用于确认的反义词>那个.但我对第5行和第6行有严重怀疑.允许显式调用析构函数,不是吗?但在此之后,对象的生命周期是否已经完成?也就是说,在析构函数的显式调用允许(定义)后调用另一个成员?
总而言之,上述代码的哪些部分(如果有的话)会导致未定义的行为(从技术上讲)?
解决方法:
p->~SomeClass(); //line 5
p->CommitSuicide(); //line 6
第(6)行肯定会调用未定义的行为.
That is, is invocation of another member after the explicit call of the destructor allowed (defined)?
没有!你的假设是正确的.
标签:self-destruction,c,destructor,delete-operator 来源: https://codeday.me/bug/20190928/1829582.html