D structs weak identity and RAII
Boris-Barboris via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sun Jun 18 18:22:10 PDT 2017
Hello, I was trying to write some templated unique pointers.
Idea was simple: struct UniquePointer that handles underlying
pointer in RAII-style and WeakPointer struct that is spawned by
UniquePointer. Weak pointer is handled differently in my
collections, wich subscribe to the event of UniquePointer
destruction, so that there are no dangling references left all
over the heap (I use Mallocator). Collection's insertFront\Back
methods register callbacks in Weak pointer itself, and all
existing weak pointers are registered in Unique pointer.
That, unfortunately, failed at the very beginning. Then I wrote a
unit test to investigate:
https://dpaste.dzfl.pl/d77c72198095
1). line 47 and 76 together mean, that there is basically no
reliable way to write uniqueptr method wich returns WeakPointer,
registered by the correct pointer in it's constructor. Or is
there? Is usage of &this in constructor (or in struct methods in
general) fundamentally unreliable in D?
2). postblit was never called when returning struct from
function. I noticed it was called once on line 91, if i removed
opAssign with ref argument. What are the rules? Why is it always
called when passing struct to function and creating local copy of
the parameter (lines 113, 127, 139), and why is opAssign not
called?
3). Is there a way to reliably encapsulate all assignments? Looks
like complete mess will happen should I apply some std.algorithm
functions on array of structs with overloaded operators.
4). Any suggested workarounds? I never tried it in C++, but,
IIRC, struct life cycle is much more consistent there ang gives
the strict control I desire.
5). If all this is a design choice, what is the reason behind it?
More information about the Digitalmars-d-learn
mailing list