delete this

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hello everyone,


Just interested to learn how C++ implements delete this statement
internally. From logical point of view, I can not imagine how to implement a
component which destroy itself.

What makes me confused is the component is relying on itself even in the
process of destroy, how could it destroys itself from itself?

thanks in advance,
George
 
Internally it is simple.

delete this
=
call ThisClass::~ThisClass () ; // Destructor
free (this) ; // deallocation

It's like you're calling from anywhere else.
Of course , "delete this" must be the last statement using object
members(data or function) in the procedure you are in, because "this"
pointer is no more valid after the deletion.

delete this is usually usefoul with reference counted objects (as in
COM), but I won't suggest it's use anywhere else. You could probably
see a "delete this" in the Release function of COM objects.

Good bye
QbProg
 
QbProg said:
Internally it is simple.

delete this
=
call ThisClass::~ThisClass () ; // Destructor
free (this) ; // deallocation

It's like you're calling from anywhere else.
Of course , "delete this" must be the last statement using object
members(data or function) in the procedure you are in, because "this"
pointer is no more valid after the deletion.

delete this is usually usefoul with reference counted objects (as in
COM), but I won't suggest it's use anywhere else. You could probably
see a "delete this" in the Release function of COM objects.

One other thing to mention about 'delete this' - it's treading very close to
undefined behavior, but it's a commonly used idiom. The key to having it
work is that 'delete this' must be the very last statement executed in the
function. Any further use of the object afterwards has undefined behavior.

-cd
 
Back
Top