c++ - 如果 "delete this"不需要访问 "somethings",那么在 "this"之后做某事是否安全?

标签 c++ memory-management undefined-behavior retain-cycle

例如,我有一个具有保留计数的类和一个释放方法,如果保留计数为 0,该方法可以删除自身:

class MyClass{
public:
    void retain(){
        this->retainCount++;
    }

    void release(){
        this->retainCount--;
        if(this->retainCount==0){
            delete this;
        }

        printf("release called");
        MyClass::deleteCount++;
        FileOutputStream* fio=new FileOutputStream();
        fio->generateLog();
        delete fio;
        EmailUtils::sendEmailAboutMemoryUsage();
    }
protected:
    int retainCount;
    static int deleteCount;
}

删除对象后我可能需要做一些代码:

printf("release called");
MyClass::deleteCount++;
FileOutputStream* fio=new FileOutputStream();
fio->generateLog();
delete fio;
EmailUtils::sendEmailAboutMemoryUsage();

我的问题是,如果删除后的代码块不需要任何访问权限,那么删除对象后继续执行代码是否安全?

最佳答案

Here's an entry of the isocpp FAQ about this issue.

As long as you’re careful, it’s okay (not evil) for an object to commit suicide (delete this).

基本上,如果您在delete this 之后没有调用任何成员函数或访问任何成员变量,它可能没问题。

查看链接了解详情。

关于c++ - 如果 "delete this"不需要访问 "somethings",那么在 "this"之后做某事是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37340238/

相关文章:

memory-management - 为什么访问未映射的位置不会产生硬件异常 (Microblaze)

在 C 中重新分配内存时编译中断

c++ - 通过指针运算访问结构体数据成员

C++ ISO 对指向基的解除引用指针的标准解释

c++ - 透明的算子仿函数

将 iPhone 保存全尺寸图像到文档目录会挂起我的应用程序

c++ - QObject在删除时是否区分堆栈和堆分配的 child ?

c++ - FFTW 导出智慧文件但无法加载

c++ - Boost::spirit 无法识别可选表达式

c - printf() 的字符串宽度对于未终止的字符串是否安全?