全部博文(47)
分类: C/C++
2006-02-23 21:30:31
最近碰到一个尴尬的事情,instances没人管,只能自己delete自己。
这里讨论了delete this语句。最后说明的使用场合很有用。
现在引入一个叫garbage的静态机制。来处理无用的instances,避免了delete this, 毕竟比较丑陋。
PROBLEM: Sharma Kunapalli
I know that "delete this" inside a member function does not make much sense when only a single process is involved, but how about when there are several processes involved that are talking to each other? Is this bad practice anyways?
RESPONSE: pete@genghis.interbase.borland.com (Pete Becker)
The fundamental issue here is not whether to use 'delete this', but how to manage objects so that they exist as long as needed and not much longer. That's an architectural issue, not a language issue. 'delete this' can serve as a minor optimization in a reference counted scheme, but the dangers that it presents would make me tend to avoid it.
RESPONSE: clamage@Eng.Sun.COM (Steve Clamage), 7 Dec 94
Considering how often this is asked, this question ought to be in the FAQ. (Marshall, are you there?)
Your program will crash (or behave strangely)
if the object - was not created with 'new';
- is a member of an array created with 'new[]';
- is later the object of an explicit 'delete';
- is referenced anyplace after the 'delete', such as by the function which invoked the cleaner.
Calling the cleaner from another member function would be particularly interesting :-) Sometimes you can be sure that it is safe to 'delete this'. In general, it is dangerous.