Move Constructor Syntax
Arafel
er.krali at gmail.com
Tue Oct 15 17:52:43 UTC 2024
On 15/10/24 18:32, Manu wrote:
> void main() {
> S s1, s2, s3;
> int i = 1;
> s1 = S(1);
> s2 = S(i);
> s3 = S(s1); // This was most certainly not intended as a
> move constructor.
> }
> ```
>
>
> Your example is a valid move constructor though... so even if the S(S)
> case were reinterpreted under the new move semantics, it's fine. It's
> almost impossible to imagine such an example where this isn't true.
>
AIUI a move constructor invalidates the source (i.e. it has ref
semantics). I would certainly expect to be able to use `s1` after `s3`
has been constructed, just like `i`.
> A _Move Constructor_ is a struct member constructor that moves,
rather than copies, the argument corresponding to its first parameter
into the object to be constructed. The argument is invalid after this
move, and is not destructed.
There is also the issue with throwing: what happens if the templated
constructor throws?
>
> This example might seem artificial, and it is, but just imagine any
> templated constructor that uses DbI, and where the own type matches.
>
> The actual inner details (i.e. that `S` is instantiated) might be even
> unknown to the caller, for instance if it comes from the user side
> of an
> API through a templated function using IFTI.
>
> Also, you cannot use `ref` because you want it to accept both r- and
> l-values, and in any case there might be good reasons why this isn't
> desirable in metaprogramming.
>
>
> That's what auto ref is for, if this specifically is your problem... and
> as I described before; there's a quite likely chance that instances of
> this pattern in the wild were actually written by D amateurs, and the
> code is actually broken, or doesn't actually quite do what they think
> they were trying to do.
>
Again the issue I see is that a move constructor invalidates the source.
In a generic templated expression that would be a special case:
```d
struct S {
this(T)(T t) { } // This now has special semantics when T == S
}
```
One possible option would be to consider only non-templated constructors
as move constructors, but even then what happens if you need both a
non-move templated constructor and a templated one with value semantics?
In any case, I personally feel a demeaning tone when referring to "D
amateurs" that doesn't exactly help. Be it as it may, even if wrong,
there can be generic code like this out there that works well enough for
its purpose.
Curtly ordering these "amateurs" to change it is not what I would call
"user-friendly".
More information about the Digitalmars-d
mailing list