Newbie initial comments on D language - destructor usage

Janice Caron caron800 at googlemail.com
Tue Jan 29 00:03:43 PST 2008


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. In the C++ case, such code is legitimate
/only/ if the programmer guarantees that MyHeapClass is always
allocated on the heap and never on the stack. (It's a useful thing to
do for thread classes, so that threads can delete themselves without
needing a separate manager class). But of course, there is no way for
the compiler to enforce this. But that's C++ and this is D.
Nonetheless, I think there's an analogy, which is that, if you, the
programmer, /know/ that you are /always/ going to explicitly call
delete, and never rely on the gc to dispose of the class, then you can
make more assumptions about what will still be valid at destructor
time. You are quite right that the compiler has no way to enforce
this, however, so I'd put it down to one of those "exotic" programming
techniques, only ever useful in rare circumstances.

I have never used that feature. If I want my class to have a manual
clean-up function, I'll generally write a function called close().



More information about the Digitalmars-d mailing list