是否允许delete this;delete-statement是将在该类实例上执行的最后一个语句?当然,我确信this-pointer所代表的对象是newly-created.
我在考虑这样的事情:
void SomeModule::doStuff()
{
// in the controller, "this" object of SomeModule is the "current module"
// now, if I want to switch over to a new Module, eg:
controller->setWorkingModule(new OtherModule());
// since the new "OtherModule" object will take the lead,
// I want to get rid of this "SomeModule" object:
delete this;
}
Run Code Online (Sandbox Code Playgroud)
我可以这样做吗?
c++ memory-management new-operator self-destruction delete-operator
以下使用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();
}
Run Code Online (Sandbox Code Playgroud)
我认为main中的前4行代码不会导致未定义的行为(尽管不完全确定delete this;).我想要确认或<占位符确认的反义词>.但我对第5行和第6行有严重怀疑.允许显式调用析构函数,不是吗?但在此之后,对象的生命周期是否已经完成?也就是说,在析构函数的显式调用允许(定义)后调用另一个成员?
总而言之,上述代码的哪些部分(如果有的话)会导致未定义的行为(从技术上讲)?