Hi,
Actually, 'delete this;' is legal. The compiler doesn't mind, and would
really delete 'this'. But it's stupid under most situation. see the
following from
http://www.progsoc.uts.edu.au/lists/progsoc/2000/October/msg00010.html
Title: RE: [ProgSoc] delete self in c++
Yeah it's okay to do this .. it's most often used inside
the constructor to destroy the object if the object itself
isnt valid.
Generally speaking, I'd recommend against using "delete this" in code.
The main problem is that the object can only be created via "new". If
the object is declared "auto" (i.e. not a pointer or reference) and
"delete this" is called it will fail because "this" was not allocated
with new and the program will crash. If you really want to use "delete
this" in your own code, make the destructor protected, preventing other
classes from deleting the object and causing a compiler error if an
auto variable of this class is ever declared.
If you want to use in it a constructor, I'd recommend against it for
the above reason and also because the calling function has no way of
knowing whether the object encountered an error - calling one of the
object's functions will result in a crash. The object fails to
instantiate itself will have to modify some form of global variable
such as errno, SetLastError(), IErrorInfo, etc, which, although
acceptable, is hardly ideal.
A much better way to report an error in an object's constructor is to
use a static "factory" function to encapsulate the construct. E.g.
static Dog* Dog::CreateDog(int legs) which can return a NULL pointer on
an error.
Alternatively, the constructor could throw an exception. Don't worry
about memory leaks, ANSI-compliant compilers should automatically
deallocate the object with calling the constructor if a newed object
throws an exception in its constructor. Check your compiler doco for
this.
The only situation I've seen "delete this" where I consider it an
acceptable use is the the thread or window classes from MFC. The
intention with these classes is to instantiate them, remove all
references to them and let the objects manages their own lifespans.
Also a good idea to check for null after any member function
that could cause the object to be destroyed.
I haven't got ARM (or a similar tome) handly but I suspect that
modifying "this" in a member funcion is illegal. Either way, changing
"this" in a member function will not affect the value of the pointer
the function was called through. E.g.
void zero_ptr(char* s)
{
// This line only changes the local version of s.
s = NULL;
}
....
char *s = "Hello, world!";
zero_ptr(s);
printf(s); // Shows "Hello, world!"
Anthony Langsworth
Software Developer
Computing Edge
mailto:
[email protected]