`delete this;`语句期间发生了什么? [英] What is happening during `delete this;` statement?

查看:101
本文介绍了`delete this;`语句期间发生了什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码:

class foo
{
public:
    foo(){}
    ~foo(){}
    void done() { delete this;}
private:
    int x;
};

在以下两个选项中发生了什么(有效)?

What is happening (and is it valid?) in the following two options:

选项1:

void main()
{
   foo* a = new foo();
   a->done();
   delete a;
}

选项2:

void main()
{
   foo a;
   a.done();
}

选项1的第二个delete a;语句会导致异常或堆损坏吗?

Will the second delete a; statement at option 1 will cause an exception or heap corruption?

option2会导致异常或堆损坏吗?

Will option2 cause an exception or heap corruption?

推荐答案

delete this;是允许的,它将删除对象.

delete this; is allowed, it deletes the object.

这两个代码段均具有未定义的行为-第一种情况是删除已删除的对象,第二种情况是删除具有自动存储期限的对象.

Both your code snippets have undefined behavior - in the first case deleting an object that has already been deleted, and in the second case deleting an object with automatic storage duration.

由于行为是不确定的,因此标准没有说明它们是否会导致异常或堆损坏.对于不同的实现,它可以是一个或两个都不是,也可以是两者,并且每次运行代码时可以相同,也可以不相同.

Since behavior is undefined, the standard doesn't say whether they will cause an exception or heap corruption. For different implementations it could be either, neither, or both, and it may or may not be the same each time you run the code.

这篇关于`delete this;`语句期间发生了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆