Is it legal to destroy yourself? Well, yes. Operator delete
needs pointer to object, and this is constant pointer to
object. So the question is, whether it is nice to use this way of removing
old objects?
Of course, there is no one answer to this problem. Some may say yes,
and some might say no. Now, why some of programmers say it's a bad thing
to do that?
Well, an object with this expression is similar to fire&forget air
to air missiles.
You can create new object, and you don't have to worry about nothing else,
especially, remembering the pointer and removing the object. This is
perfect tool for, i.e. popup window, which automatically removes itself
after pressing OK button.
But there are two problems that a programmer should be aware using this
expression. The first thing is he can forget that those objects can be
created only dynamically, and define automatic, static or global object.
This will cause system to crash and the reason may hard to trace for
someone who doesn't know or forgot about it.
The second thing is what will happen in case of exception being raised?
The object will stay and won't be cleaned up, even if it's logical context
is gone. For example, if the object is to calculate a eigen values of
matrix hold by another object, and the latter will be removed due to
error, it will cause access violations, or in the best case, many unneeded
calculations. The only solution to prevent leaving the object is cleaning
using some lists. But this is uncool.
Conclusion: use the expression only when you know what you are doing,
keep in mind that you cannot create new objects statically, remember to
tell about it anyone who will use your code, and use it only if the object
has no particular external context.
|