rvalue based copy

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Mar 30 10:21:51 PDT 2015


On 3/30/15 1:09 PM, matovitch wrote:
> Hi,
>
> Surely I am misunderstanding something.
>
> I got something like this :
>
> struct S
> {
>      void opAssign(const ref s)
>      {
>          //...
>      }
> }
>
> S genS()
> {
>      S s;
>      //...
>      return s;
> }
>
> main()
> {
>      S s;
>      s = genS();
> }
>
> DMD says : ...opAssign (ref const(S) point) is not callable using
> argument types (S).
>
> Then how to do what I wanna do ? Why doesn't this works ? (I am gessing
> ref argument explitly means no rvalue)
>
> Thanks in advance for your help ! :)

One solution is to overload

void opAssign(ref const S s) {...}
void opAssign(const S s) {...}

lvalues will go into the ref version, rvalues into the non-ref. There 
won't be any copying of data, so you still save a postblit and copying 
on the stack.

But you have to repeat the implementation.

Another possibility is to use auto ref, but that requires a template. 
Annoying as this is (and blatantly awkward), it saves you from having to 
implement twice:

void opAssign(T)(auto ref const T s) if(is(T == S)) {...}

-Steve


More information about the Digitalmars-d-learn mailing list