小编典典

C++ 中是否允许“删除这个”?

all

delete this;如果删除语句是将在该类的实例上执行的最后一条语句,是否允许?当然,我确定由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;
}

我可以这样做吗?


阅读 142

收藏
2022-05-20

共1个答案

小编典典

C++ FAQ Lite 有一个专门用于此的条目

我认为这句话很好地总结了它

只要你小心,一个对象自杀是可以的(删除这个)。

2022-05-20