Andrej Mitrovic wrote: >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?
Strange, I can confirm this behavior and it seems to happen all the time when using RefCounted. I guess this was never an issue for the RefCounted code in phobos (for example std.container.Array) as RefCounted was only used to manage memory, not handles from C libraries. free simply does nothing if called with a null pointer, so this problem never showed up. As a workaround, check your handle against null in the destructor before calling the function to close the handle. -- Johannes Pfau