Wednesday 10 April 2013

Question: What is your reaction to this line of code? delete this;


Question: What is your reaction to this line of code? delete this;
 Answer: It is not a good programming Practice.

A good programmer will insist that you should absolutely never use the statement if the class is to be used by other programmers and instantiated as static, extern, or automatic objects. That much should be obvious.

The code has two built-in pitfalls. First, if it executes in a member function for an extern, static, or automatic object, the program will probably crash as soon as the delete statement executes. There is no portable way for an object to tell that it was instantiated on the heap, so the class cannot assert that its object is properly instantiated. Second, when an object commits suicide this way, the using program might not know about its demise. As far as the instantiating program is concerned, the object remains in scope and continues to exist even though the object did itself in. Subsequent dereferencing of the pointer can and usually does lead to disaster. I think that the language rules should disallow the idiom, but that's another matter.
  

No comments:

Post a Comment