如果你做“删除这个”会发生什么;在成员函数中? [英] what will happen if you do "delete this;" in a member function?

查看:122
本文介绍了如果你做“删除这个”会发生什么;在成员函数中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果成员函数尝试执行 delete this; ,类似于下面类的构造函数,会发生什么?

What will exactly happen if a member function try to do delete this;, like in the constructor of the following class?

class A
{
public:
    A(int);
    ~A();
    int *pi;
}

A::A(int i)
{
    delete this;
    pi = new int(i);
}

A::~A()
{
    delete pi;
}


推荐答案

C ++常见问题解答很好地回答了这一点,在此复制:

This C++ FAQ entry answers this quite nicely, replicating the same here:

只要你小心,对象可以自杀( delete this )。

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

以下是我如何定义仔细:

Here's how I define "careful":


  • 100%肯定肯定这个对象是通过新的(不是由新的[],也不是通过放置new,也不是一个局部对象在堆栈,也不是一个全局,也不是​​另一个对象的成员,而是通过普通的新的)。

  • 您必须绝对100%肯定您的成员函数将是此对象上调用的最后一个成员函数。

  • 您必须绝对100%肯定您的成员函数的其余部分(删除此行后)不会触及此对象的任何部分调用任何其他成员函数或触摸任何数据成员。)

  • 您必须绝对100%肯定,没有人甚至触摸this指针本身删除此行。换句话说,你不能检查它,与另一个指针进行比较,比较它与NULL,打印,铸造它,做任何事情。

  • You must be absolutely 100% positively sure that this object was allocated via new (not by new[], nor by placement new, nor a local object on the stack, nor a global, nor a member of another object; but by plain ordinary new).
  • You must be absolutely 100% positively sure that your member function will be the last member function invoked on this object.
  • You must be absolutely 100% positively sure that the rest of your member function (after the delete this line) doesn't touch any piece of this object (including calling any other member functions or touching any data members).
  • You must be absolutely 100% positively sure that no one even touches the this pointer itself after the delete this line. In other words, you must not examine it, compare it with another pointer, compare it with NULL, print it, cast it, do anything with it.

您通过访问 pi #3 c> 之后删除此

这篇关于如果你做“删除这个”会发生什么;在成员函数中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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