Newbie initial comments on D language - destructor usage

James Dennett jdennett at acm.org
Tue Jan 29 20:43:54 PST 2008


Edward Diener wrote:
> Janice Caron wrote:
>> On Jan 29, 2008 12:52 AM, Edward Diener
>> <eddielee_no_spam_here at tropicsoft.com> wrote:
>>> Except for a
>>> 'scope' class a destructor can not possibly know how it is being called
>>
>> True.
>>
>> Nonetheless, I have seen code in C++ which does:
>>
>>     ~MyHeapClass()
>>     {
>>         delete this;
>>     }
>>
>> even though the destructor cannot possibly know whether or not the
>> class was allocated with new. 
> 
> I completely agree the above is bad C++ code, and can only be possibly 
> considered correct if some rule says that the class can never be created 
> except in dynamic memory. 

Not even then; "delete this" is not valid from within a destructor,
as the destructor has already set about destroying the object, and
so attempting to re-destroy the object makes no sense.

It's safe to use "delete this" in response to an object being told
to drop the last reference to itself, but it makes no sense to do
so from its own destructor.

I suspect Janice just mis-quoted some C++ code, moving "delete this"
to somewhere it doesn't belong.

-- James



More information about the Digitalmars-d mailing list