TDPL: Manual invocation of destructor

Andrej Mitrovic andrej.mitrovich at gmail.com
Sun Aug 8 12:07:13 PDT 2010


One more thing:

Is it possible for the compiler to detect missing constructors in a class?

E.g.:

class A
{
    static A a1;
    static A a2;

    static ~this()
    {
        clear(a1);
    }

    static ~this()
    {
        clear(a2);
    }

}

void main() { }


This will cause an object access violation in runtime.

On Sun, Aug 8, 2010 at 8:09 PM, Andrej Mitrovic
<andrej.mitrovich at gmail.com>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?
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d/attachments/20100808/c0989088/attachment.html>


More information about the Digitalmars-d mailing list