Contents Up << >>

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

As long as you're careful, you'll be ok.

Here's how I define "careful":

1) You're absolutely 100% positively sure that "this" was allocated via "new" (not by "new[]", nor by placement " new", but by plain ordinary "new").

2) You're absolutely 100% positively sure that your member function will be the last member function invoked on this object.

3) After you do the suicide thing ("delete this;"), you must not touch any piece of "this" object, including data or methods.

4) After you do the suicide thing ("delete this;"), you must not touch the "this" pointer. In other words, you must not examine it, compare it with another pointer or with NULL, print it, cast it, do anything with it.

Naturally the usual caveats apply in cases where your "this" pointer is a pointer to a base class and the destructor isn't virtual.