Yesterday, I discussed with Alex whether “delete this” in C++ is legal code.
In some case, only the object itself knows when its life is to the end and should be destroyed, the owner of object doesn’t know it, or the object has no explicit owner. The most easy way to manger the life time of this kind of object is let it delete itself.
But we doubted that “delete this” isn’t legal in C++: after the object is released, how does the execution continue?
1 | class A { |
I find the answer now, it’s legal, but must be careful when using it.
The following faq explain it clearly:
只要你小心,一个对象请求自杀(
delete
this
).是可以的。
以下是我对“小心”的定义:
- 你必须100%的确定,
this
对象是用new
分配的(不是用new[]
,也不是用定位放置new
,也不是一个栈上的局部对象,也不是全局的,也不是另一个对象的成员,而是明白的普通的new
)。 - 你必须100%的确定,该成员函数是
this
对象最后调用的的成员函数。 - 你必须100%的确定,剩下的成员函数(
delete
this
之后的)不接触到this
对象任何一块(包括调用任何其他成员函数或访问任何数据成员)。 - 你必须 100%的确定,在
delete
this
之后不再去访问this
指针。换句话说,你不能去检查它,将它和其他指针比较,和NULL
比较,打印它,转换它,对它做任何事。delete
this
)。
And these ariticles also take about “delete this”:
http://info.tlw.cn/6079.htm
http://blog.csdn.net/foxmail/archive/2004/09/22/113060.aspx