Newbie initial comments on D language - destructor usage

Edward Diener eddielee_no_spam_here at tropicsoft.com
Tue Jan 29 18:51:07 PST 2008


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. Usually that rule has to do with some C++ 
compiler extension which is not standard C++ and forbids a class object 
to be instantiated on the stack. Such is the case with Microsoft's ATL 
where you will see the idiom above actually occurring in code when the 
reference count for an ActiveX object, which must be created in dynamic 
storage, goes to 0. But in general it is a horrible way of coding.



More information about the Digitalmars-d mailing list