why @property cannot be pass as ref ?

Simen Kjærås simen.kjaras at gmail.com
Wed Jan 3 08:51:55 UTC 2018


On Saturday, 30 December 2017 at 03:49:37 UTC, ChangLong wrote:
> What I am try to do is implement a unique data type. (the 
> ownership auto moved into new handle)

Have you considered std.typecons.Unique[0]? If yes, in what ways 
does it not cover your needs?

Your example code written with Unique would be something like the 
below, with some additions to show off more of what it can do:

import std.typecons : Unique;
import std.algorithm.mutation : move;

void test1(size_t i) {}
void test2(ref size_t i) {}
void test3(ref Unique!size_t i) {}
void test4(Unique!size_t i) {}

unittest
{
     static __gshared size_t socket;
     auto l1 = Unique!(size_t)(&socket);
     assert(l1 == &socket);

     Unique!(size_t) l2 = void;
     assert(!is(typeof({
         l2 = l1; // Fails to compile - cannot copy Unique.
     })));
     move(l1, l2); // Explicit move using 
std.algorithm.mutation.move.

     assert(l1 == null); // l1 has been cleared - only one 
reference to the data exists.
     assert(l2 == &socket); // l2 has the only reference.

     auto l3 = l2.release; // Implicit move, not unlike your byRef 
call.

     assert(l2 == null); // l2 has been cleared - only one 
reference to the data exists.
     assert(l3 == &socket); // l3 has the only reference.

     assert(!is(typeof({
         auto l4 = l3; // Fails to compile - cannot copy Unique.
     })));

     test1(*l3); // Can dereference and pass the pointed-to value.
     test2(*l3); // Can pass reference to pointed-to value[1].
     test3(l3);  // Lets you pass references to Unique.
     assert(!is(typeof({
         test4(l3); // Fails to compile - cannot copy Unique.
     })));
}

[0]: https://dlang.org/library/std/typecons/unique.html
[1]: This surprised me a little - that's a new reference to the 
pointed-to value, which the callee could squirrel away somewhere 
it shouldn't. I guess it's there for ease of use.

--
   Simen


More information about the Digitalmars-d-learn mailing list