TDPL: Manual invocation of destructor

Andrej Mitrovic andrej.mitrovich at gmail.com
Mon Aug 9 05:28:38 PDT 2010


It's rather perplexing, isn't it? It states in TDPL:

"After you invoke clear, the object is still alive and well, but its
destructor has been called and the object is now carrying its
default-constructed stated. During the next garbage collection, the
destructor is called again, because the garbage collector has no idea in
what state you have left the object."

But in what situation would you want to manipulate an object that was
already cleared and ready for garbage collection?

On Mon, Aug 9, 2010 at 2:16 PM, Steven Schveighoffer <schveiguy at yahoo.com>wrote:

> On Sun, 08 Aug 2010 23:16:48 -0400, Andrei Alexandrescu <
> SeeWebsiteForEmail at erdani.org> wrote:
>
>  On 08/08/2010 01:09 PM, Andrej Mitrovic wrote:
>>
>>> On Page 187 it states (shortened here for convenience):
>>> "By calling clear(b), you invoke b's destructor, obliterate the object's
>>> state with Buffer.init, and call Buffer's default constructor"
>>>
>>> On the next page there's a unittest, and the entire example is this:
>>>
>>> import core.stdc.stdlib;
>>>
>>> class Buffer
>>> {
>>>     private void* data;
>>>
>>>     // constructor
>>>     this()
>>>     {
>>>         data = malloc(1024);
>>>     }
>>>
>>>     // destructor
>>>     ~this()
>>>     {
>>>         free(data);
>>>     }
>>> }
>>>
>>> unittest
>>> {
>>>     auto b = new Buffer;
>>>     auto b1 = b;    // extra alias for b
>>>     clear(b);
>>>     assert(b1.data is null);
>>> }
>>>
>>> void main() { }
>>>
>>> The assert fails, regardless if there is another reference to the object
>>> or not (b1 in this case).
>>>
>>> I've added some writeln()'s (not shown here), and just like the book
>>> said, after clear(b), b's destructor gets called, the fields get initialized
>>> to .init, and then b's constructor gets called. But the constructor will
>>> allocate memory for b1.data again, which means data is not null anymore.
>>>
>>> So I'm guessing the assert code is wrong in the example?
>>>
>>
>> Yes, the assert is in error.
>>
>
> Wait wait, when destroying an object manually, the runtime will re-call the
> constructor?  I thought it was just going to assign the TypeInfo's initial
> value to the class?
>
> Re-calling the constructor on destruction seems like a horrible
> mis-feature.  Nobody will ever use it.
>
> -Steve
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d/attachments/20100809/8337056c/attachment.html>


More information about the Digitalmars-d mailing list