TDPL: Manual invocation of destructor
Steven Schveighoffer
schveiguy at yahoo.com
Mon Aug 9 05:16:19 PDT 2010
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
More information about the Digitalmars-d
mailing list