Move Constructor Syntax

Jonathan M Davis newsgroup.d at jmdavisprog.com
Fri Oct 11 17:16:30 UTC 2024


On Friday, October 11, 2024 9:19:54 AM MDT Manu via Digitalmars-d wrote:
> The move semantic described by the dip should apply to every rvalue
> everywhere; they're all potential move targets.
>
> Especially so for your weird
> not-a-move-constructor-but-actually-a-move-constructor that receives T by
> value; it's the exact definition of a move constructor, and it should be
> the case that concretely proves that it is also the exact proper syntax for
> the declaration!

Just because a constructor such as this(typeof(this)) looks like a move
constructor doesn't guarantee that it has those semantics. We have no clue
what the programmer chose to do in that case given that it is not currently
used as a move constructor and there was zero expectation that it ever would
be. While the obvious use case is to construct the new object with the same
value as the original, we cannot guarantee that that is what the programmer
actually did. They could have simply chosen to take parts of the original
and not the entire thing, using that constructor as a way to pass specific
parts of the object's state but not all of it, whereas with a move, they
would want the object to be moved exactly as-is. Right now, the programmer
can rely on that constructor only being called when they've explicitly
called it, and they're free to do whatever they want with it even if plenty
of other folks would think that what they did was a bad idea. Changing it so
that that constructor suddenly got called implicitly in a bunch of cases
would potentially break their code - as well as likely hurting performance,
since they were presumably fine with the move semantics that they had
previously and didn't want their constructor called in those cases.

Another issue here is the refness of the parameter. Move constructors really
should be taking their argument by ref, not by value, since it's not being
copied, and it hasn't been moved yet. However, for better or worse,
this(ref typeof(this)) is already a copy constructor. Having a separate
syntax for move constructors allows us to have it be =this(ref typeof(this))
or @move this(ref typeof(this)) or whatever, and then it's distinct from
copy constructors while still having ref like it really should.
Using this(typeof(this)) while implicitly treating the parameter as ref even
though it isn't just creates a needless special case.

- Jonathan M Davis





More information about the Digitalmars-d mailing list