why @property cannot be pass as ref ?
Ali Çehreli
acehreli at yahoo.com
Tue Jan 2 18:53:18 UTC 2018
On 12/29/2017 07:49 PM, ChangLong wrote:
> On Wednesday, 20 December 2017 at 18:43:21 UTC, Ali Çehreli wrote:
>> Thanks to Mengü for linking to that section. I have to make
>> corrections below.
>>
>> Ali
>
>
> Thanks for explain, Ali And Mengu.
>
> What I am try to do is implement a unique data type. (the ownership auto
> moved into new handle)
>
> consider this code:
>
> import std.stdio;
>
> struct S {
> @disable this(this);
> void* socket;
> this (void* i) {
> socket = i;
> }
>
> void opAssign()(auto ref S s ){
> socket = s.socket ;
> s.socket = null ;
> }
>
> @nogc @safe
> ref auto byRef() const pure nothrow return
> {
> return this;
> }
> }
>
>
> void main() {
> static __gshared size_t socket;
> auto lvalue = S(&socket); // pass rvalue into lvalue, working
> S l2 = void;
> l2 = lvalue; // pass lvalue into lvalue, working
> auto l3 = l2.byRef; // pass lvalue into lvalue, not working
> }
>
>
>
> I can not assign l2 to l3 because "Error: struct app.S is not copyable
> because it is annotated with @disable", but it working if I init l3 with
> void.
I hope others can answer that. For what it's worth, here is an earlier
experiment that Vittorio Romeo and I had played with at C++Now 2017. It
uses std.algorithm.move:
import std.stdio;
import std.algorithm;
int allocate() {
static int i = 42;
writeln("allocating ", i);
return i++;
}
void deallocate(int i) {
writeln("deallocating ", i);
}
struct UniquePtr {
int i = 666; // To easily differentiate UniquePtr.init from 0
this(int i) {
this.i = i;
}
~this() {
deallocate(i);
}
@disable this(this);
}
void use(UniquePtr p) {
writeln("using ", p.i);
}
UniquePtr producer_rvalue(int i) {
return i % 2 ? UniquePtr(allocate()) : UniquePtr(allocate());
}
UniquePtr producer_lvalue() {
writeln("producer_lvalue");
auto u = UniquePtr(allocate());
writeln("allocated lvalue ", u.i);
return u;
}
void main() {
use(UniquePtr(allocate()));
auto u = UniquePtr(allocate());
use(move(u));
auto p = producer_rvalue(0);
use(move(p));
auto p2 = producer_lvalue();
use(move(p2));
}
Ali
More information about the Digitalmars-d-learn
mailing list