Move construction from !is(T == typeof(this))

Stanislav Blinov via Digitalmars-d digitalmars-d at puremagic.com
Mon Apr 24 11:48:00 PDT 2017


On Monday, 24 April 2017 at 15:19:29 UTC, Manu wrote:

> If you're going to pinch the guts of rvalue arguments, then 
> this needs to
> be 100% reliable.
> This needs to be aggressively unit-tested, and probably 
> documented that
> this is the official pattern for rvalue construction/assignment 
> operations.

Looking over your OP again, and the report made by Petar Kirov, I 
realized this is not quite right. We can't, generally speaking, 
treat this(const ref X x) as a copy ctor.

Consider:

struct X
{
     int* ptr;
}

struct Y
{
     int* ptr;

     this(ref const X x)
     {
         // ptr == ???;
         // typeof(x.ptr) == const(int*)
         // seems like the only way to implement this is:
         // ptr = new int(*x.ptr);
     }

     this(X x)
     {
         import std.algorithm.mutation : swap;
         swap(ptr, x.ptr);
     }
}

X x;
Y y = x; // this(ref const X) is called

Suddenly, we can't copy the pointer, or at least make a shallow 
copy of it, without violating const, and the latter is UB.
The ref const overload should only be called with const lvalues, 
and it seems to be the case.
OTOH, copying with this(ref X x) will work, as will this(X), so I 
guess the proper set of overloads should be:

struct Y
{
     this(ref X x) { /*copy...*/ }
     this(X x) { /*move...*/ }
}

with possible addition of this(ref const X x) for a deep copy.

Speaking of const violation and UB, std.algorithm.mutation.move 
seems to violate const without remorse:

struct Z
{
     const int i;

     ~this() {}
}

auto z = Z(10);
auto zz = move(z);
// z.i is now 0

So, move does set z to a default-constructed state, but in doing 
so changes the value of a const variable. And there seems to be 
no other way to implement destructive move.
In case of such Z, of course the only thing you can safely do 
with z now is destruct it (not that the language can enforce it), 
so we might say it's all good...


More information about the Digitalmars-d mailing list