advise about safety of using move in an opAssign with __traits(isRef

aliak something at
Fri Aug 16 08:07:28 UTC 2019

Hi, I'm trying to fix a use-case where you have a wrapper 
template type (it's an optional) and the wrapping type has 
@disable this(this). And having this scenario work:

struct S {
   @disable this(this);
Optional!S fun() {...}

Optional!S a;
a = fun.move;

Now that won't work because of the disabled copy, but you can 

1) Add an explicit move function in the Optional type:
struct Optional {
   auto move(ref Optional!T target) {
     import std.algorithm: move;
     return move(this, target);

Then you  could do:

First of all I find the readability confusing, so there's no way 
to know if fun is moving in to field or field is moving in to 
fun. But OTOH it matches the phobos move(T src, T target). So 
conventionally maybe ok. Also it's explicit, so it makes it clear 
at the call site that a move is happening.

2) use isRef inside opAssign like this:

void opAssign(auto ref Optional!T lhs) {
   static if (__traits(isRef, lhs)) {
     this._value = lhs._value;
   } else {
     import std.algorithm: move;
     move(lhs._value, this._value);

Then you could just do:

field = fun

And it'll just work since fun returns an rvalue. The second 
solution it seems like it'll just work correctly with the static 
if guard. But I'm not sure if there're any gotchas I should be 
aware of?

Any advice?

More information about the Digitalmars-d-learn mailing list