View mode: basic / threaded / horizontal-split · Log in · Help
January 30, 2008
Re: Newbie initial comments on D language - destructor usage
On Jan 30, 2008 4:43 AM, James Dennett <jdennett@acm.org> wrote:
> I suspect Janice just mis-quoted some C++ code, moving "delete this"
> to somewhere it doesn't belong.

No wait - actually you're right.
Yes, I had moved "delete this" to the wrong place. It actually goes in
a member function, but not the destructor. From memory, the example
was a Thread class, and it called delete on return from the virtual
run() function, so that the threads resources got cleaned up after the
thread had terminated. So, thanks for the correction.

Nonetheless, it is possible (and in some cases legitimate) to call the
destructor code without the deallocator, or vice versa.

To destruct then deallocate (the normal situation)
   delete p;

To destruct without dealocating:
   p->~Whatever();
(where Whatever is typeof(*p))

To deallocate without destructing:
  operator delete(p);

Whether or not this is useful is another question.

I don't know if the same distinctions can be made in D (or even
whether or not we'd want them). In any case, it's all very off-topic
with regard to the original question, so my apologies for the
digression. And now back to our regularly scheduled discussion...
January 30, 2008
Re: Newbie initial comments on D language - destructor usage
James Dennett wrote:
> Edward Diener wrote:
>> Janice Caron wrote:
>>> On Jan 29, 2008 12:52 AM, Edward Diener
>>> <eddielee_no_spam_here@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.

You are completely correct and it was my error also in not noticing that 
this was done in the destructor itself.
Next ›   Last »
1 2
Top | Discussion index | About this forum | D home