FAQ 12.18 Is it legal (and moral) for a member function to say delete this ?

FAQ 12.18 Is it legal (and moral) for a member function to say delete this?

Yes, but be careful.

Programmers usually have a hard time emotionally accepting that this is valid, probably because it seems as if the member function is inside the object and deleting the object during a member function seems strange. But with care, this technique can be perfectly safe. Here is how we define "with care."

  1. The this object must have been allocated via new (see FAQ 12.15), not by new[] (see FAQ 12.11) nor by placement new (see FAQ 12.14) nor by a local object on the stack nor by a global nor by a member of another object. It has to have been allocated by plain, ordinary new.

  2. The member function that contains delete this; must be the last member function that is invoked on the this object.

  3. The remainder of the member function after the delete this; line must not touch any piece of the this object, including calling any other member functions or touching any data members.

  4. No other piece of code should even examine the this pointer itself after the delete this; line. No one may examine it, compare it with another pointer, compare it with NULL, print it, cast it, do anything with it.

  5. Make sure no one else does a delete on the object. For example, if the object is still being held by an auto_ptr (which would be a good thing!), the release() member function must be called on the auto_ptr; otherwise the auto_ptr will delete the object again, which would be a disaster. For example:

     #include <iostream> using namespace std; class Fred { public:   Fred();   virtual ~Fred();   virtual void discard() throw(); }; void Fred::discard() throw() { delete this; } 


C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net