c++ - C++ 允许使用 "delete this"吗?

标签 c++ memory-management new-operator delete-operator self-destruction

是否允许 delete this; 如果 delete 语句是将在该类实例上执行的最后一条语句?当然,我确信 this 指针表示的对象是 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;
}

我可以这样做吗?

最佳答案

C++ FAQ Lite 有专门针对此的条目

我认为这句话很好地概括了它

As long as you're careful, it's OK for an object to commit suicide (delete this).

关于c++ - C++ 允许使用 "delete this"吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49593571/

相关文章:

c++ - C++中变量的声明

iPhone - 为什么静态分析器没有选择它?

c - 进程中如何动态分配内存变量?

c++ - 在单个分配中分配一个包含字符串的结构

c++ - 我想我可以理解 N4140 中的 §5.3.4/11,但是扩展的分配函数的概念对我来说是不可理解的

c++ - delete[] 字符数组

c++ - 如何从父模板函数访问子成员?

c++ - 将 unsigned char 数组的元素作为整数访问

c++ - 从spinbox保存数据

c++ - 为什么将对象地址存储在缓冲区中会在实例化和删除它们时导致内存泄漏?