Reference counting questions

Andrej Mitrovic andrej.mitrovich at gmail.com
Sun Jul 24 15:52:50 PDT 2011


I'm don't understand why this code calls the dtor before it calls the ctor:

import std.stdio;
import std.typecons;

void main()
{
    auto wrap1 = Wrapper(1);
}

void free(ref int _payload)
{
    writeln("dealloc");
    _payload = 0;
}

struct Wrapper
{
    struct Payload
    {
        int _payload;
        this(int h) { writeln("alloc"); _payload = h; }
        ~this() { free(_payload); }

        this(this) { assert(false); }
        void opAssign(Wrapper.Payload rhs) { assert(false); }
    }

    private alias RefCounted!(Payload, RefCountedAutoInitialize.no) Data;
    private Data _data;

    this(int h) { _data = Data(h); }
}

prints:
dealloc
alloc
dealloc

What's with the first dtor call?


More information about the Digitalmars-d-learn mailing list