Topic: delete this' in member functions


Author: jbuck@forney.berkeley.edu (Joe Buck)
Date: 19 Jul 91 23:07:18 GMT
Raw View
I decided to post this to comp.std.c++ as well as comp.lang.c++.


In article <358@lax.lax.pe-nelson.com> twbrown@PE-Nelson.COM (Tom W. Brown) writes:
>I like the 'delete this' approach and I don't want to change it unless it
>truly is illegal or undefined by the language.

I've looked through the ARM and can't find anything either blessing or
forbidding it, but knowing a little bit about C++ implementation I'm
concerned that such code may not be portable.  Why?  Because delete,
when applied to an lvalue, is allowed to change the value of the pointer
(perhaps to trap references to deleted objects), and the compiler may
end up putting other references to the object after the delete this
statement in the standard epilog code.  I think, though, that on most
implementations, if delete this is the last statement of a member function
it will be safe.

On page 279, in discussing explicit destructor calls (needed only when
you overload new to allow an object to be placed in preexisting memory),
the example

void X::f() {
 ...
 this->~X();  // destroy `*this'
 ...
}

appears.  Note that this is not a delete, but it implies that C++
compilers must be prepared for a destructor to be called by an object
on itself.

I think that this is a question that the ANSI C++ committee needs to
clear up (unless it's in the ARM already and I missed it).

I'd appreciate either a pointer to the spot in the ARM that I've missed,
a description from ANSI C++ people as to what they've decided, or a
message from Bjarne saying what he intended.

--
--
Joe Buck
jbuck@galileo.berkeley.edu  {uunet,ucbvax}!galileo.berkeley.edu!jbuck