Move Constructor Syntax
Timon Gehr
timon.gehr at gmx.ch
Wed Oct 16 13:06:07 UTC 2024
On 10/16/24 08:44, Arafel wrote:
> On 16/10/24 2:43, Timon Gehr wrote:
>> You are right assuming move constructors work as shown in DIP1040.
>> However, I think this design is not really workable, and I think Manu
>> is arguing from a position of assuming that the argument needs to
>> remain valid and will be destroyed by default.
>
> Please excuse the question
No worries!
> if it sounds too obvious (no irony here, I'm
> absolutely no expert in language design), but if the argument remains
> valid, and can be destroyed or not, doesn't it become a copy constructor?
A copy constructor is expected to result in two objects that represent
the same value.
A move constructor is expected to result in the original object in a new
memory location. With Walter's current preferred design, a new dummy
object is created in the old memory location. I.e., it has to be valid,
but it does not have to contain any data. For example, if you move an
array with 3 elements from location A to location B, then location B
will contain the original array while location A will contain an empty
array.
With copy construction, both locations would contain two equal arrays
with 3 elements, both equal to the original array.
The question of whether a value is _valid_ is distinct from the question
whether a value is useful. For example, in D `null` is a valid value for
a class reference.
This enables moving objects out of memory locations that may still be
reachable later, such as a field of a class object.
If the dummy object is required to be a value that does not need, yet
allows (no-op) destruction, the compiler has a bit of leeway in how it
calls destructors. It is also the least surprising behavior for the case
where we move a class field, as a class finalizer may never even run.
A key difference between `this(S s)` and `=this(ref S)` is that the
latter elides the destructor by default, while for the former, the least
surprising semantics would be that it calls the destructor of the source
at the end of the scope by default. There would then need to be an
additional feature to elide the destructor call with manual syntax.
More information about the Digitalmars-d
mailing list