ggr*_*grr 3 c++ memory-management undefined-behavior retain-cycle
例如,我有一个具有保留计数的类和一个可以在保留计数为0时删除self的释放方法:
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;
}
Run Code Online (Sandbox Code Playgroud)
在删除对象后,我可能会有一些代码要做:
printf("release called");
MyClass::deleteCount++;
FileOutputStream* fio=new FileOutputStream();
fio->generateLog();
delete fio;
EmailUtils::sendEmailAboutMemoryUsage();
Run Code Online (Sandbox Code Playgroud)
我的问题是,如果删除后的代码块不需要任何访问,那么在删除对象后继续执行代码是否安全?
只要你小心,对象自杀就可以了(不是邪恶的)(删除它).
基本上,如果您之后没有调用任何成员函数或访问任何成员变量delete this
,那么它可能没问题.
请参阅链接了解详细信息.
这是完美定义的行为,前提是您可以确定您的对象已被分配new
.
在这种情况下,它调用析构函数并释放与对象相关联的内存,从而this
形成悬空指针.由于您在删除后没有访问它,因此代码中没有立即出现的问题.
但是你应该至少在该方法中添加一个强烈的通知,因为即使是安全的,你应该警告未来的维护者现在这两个不可破解的规则:
this
非静态方法的任何成员变量delete this