OT: Calling delete on 'this' from member function
Daniel Keep
daniel.keep.lists at gmail.com
Sun May 13 16:11:56 PDT 2007
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. (Plus,
you can't use this on any class with invariants or they'll blow up.)
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.
-- Daniel
--
int getRandomNumber()
{
return 4; // chosen by fair dice roll.
// guaranteed to be random.
}
http://xkcd.com/
v2sw5+8Yhw5ln4+5pr6OFPma8u6+7Lw4Tm6+7l6+7D
i28a2Xs3MSr2e4/6+7t4TNSMb6HTOp5en5g6RAHCP http://hackerkey.com/
More information about the Digitalmars-d
mailing list