OT: Calling delete on 'this' from member function

Vladimir Panteleev thecybershadow at gmail.com
Sun May 13 18:29:45 PDT 2007


On Mon, 14 May 2007 02:11:56 +0300, Daniel Keep <daniel.keep.lists at gmail.com> wrote:

>
>
> Vladimir Panteleev wrote:
>> On Sun, 13 May 2007 18:23:13 +0300, Regan Heath <regan at netmail.co.nz> wrote:
>>
>>> One further question, is it actually valid to call delete this in a non-static method of a class as shown below.  It seems to work but I would not have thought it possible...
>>
>> I don't see why this wouldn't work, with the condition that you don't access class fields or virtual methods after deleting the object (this includes invariants). The above might work in very specific circumstances, but you should never rely on accessing data marked as deallocated.
>
> The problem I can see with this is that *something* must still have a
> reference to the object, otherwise the method couldn't have been called.
>  And if that's the case, that reference is now left dangling.

Not really. The object context, aka "this", is nothing more than a "hidden" function parameter. Classes are just pointers to structs with VMTs. So "delete this" isn't different than deallocating something the reference to which was given to you as a function parameter. The same logic applies - the calling code shouldn't use the object reference after calling the function/method, just like you wouldn't use a reference after you delete it explicitely :)

> I suppose, if you were careful, it would be OK.  But frankly, it just
> seems wrong... a bit like returning pointers to local variables based on
> the assumption they get used before calling something else; technically
> feasible, but just *asking* for problems.

Returning pointers to local variables is comparable to this situation only when you actually DO use the class's fields or virtual methods after you delete it. Just like with the stack, memory has been deallocated but usually not overwritten. In pre-multi-tasking OSes (MS-DOS specifically), using data left in the callees' stacks had a real risk of being overwritten by hardware interrupt handlers.

-- 
Best regards,
  Vladimir                          mailto:thecybershadow at gmail.com



More information about the Digitalmars-d mailing list