D's equivalent to C++'s std::move?

Dicebot via Digitalmars-d digitalmars-d at puremagic.com
Mon Feb 1 05:34:09 PST 2016


On Monday, 1 February 2016 at 13:21:02 UTC, Shachar Shemesh wrote:
> Hi all,
>
> I have a non-copyable struct with move semantics. In other 
> words, a struct with @disable this(this), but with working 
> overloads for the this(copy) and opAssign.
>
> Now I have an instance of that struct. I would like to be able 
> to voluntarily give up ownership for the sake of another 
> instance.


auto move (T) (ref T origin)
     if (is(T == struct))
{
     scope(exit) origin = T.init;
     return T(origin.tupleof);
}

// example:

struct S
{
     int* x;
     @disable this(this);
}

void foo (S s) { }

void main()
{
     auto s = S(new int);
     // won't compile, postblit is disabled:
     foo(s);
     // but this works, because rvalues are always moved:
     foo(move(s));
     assert(s.x is null);
}


More information about the Digitalmars-d mailing list