例如,我有一个具有保留计数的类和一个释放方法,如果保留计数为 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/