Move Constructor Syntax
Jonathan M Davis
newsgroup.d at jmdavisprog.com
Mon Oct 7 18:56:49 UTC 2024
On Sunday, October 6, 2024 10:43:34 AM MDT Paul Backus via Digitalmars-d
wrote:
> On Sunday, 6 October 2024 at 04:04:28 UTC, Walter Bright wrote:
> > As the above illustrates, a move constructor cannot be
> > distinguished from a regular constructor by syntax alone. It
> > needs semantic analysis.
>
> It's worth pointing out that this is not just a problem for move
> constructors; it's also a problem for copy constructors.
> Specifically, it's what prevents copy constructors from being
> templates.
>
> As a result, if you're writing generic code and want to handle
> arbitrary combinations of type qualifiers on the original object
> and the copy, you cannot do the simple, obvious thing and use a
> template, like this:
>
> this(this This, Other)(ref Other other)
> if (is(immutable Other == immutable typeof(this))
> {
> // copy logic
> }
>
> Instead, you must write individual copy constructor overloads for
> every combination of qualifiers:
>
> // Function bodies omitted for brevity
> // mutable original
> this(ref typeof(this));
> this(ref typeof(this)) const;
> this(ref typeof(this)) immutable;
> this(ref typeof(this)) inout;
>
> // const original
> this(ref const typeof(this));
> this(ref const typeof(this)) const;
> this(ref const typeof(this)) immutable;
> this(ref const typeof(this)) inout;
>
> // immutable original
> this(ref immutable typeof(this));
> this(ref immutable typeof(this)) const;
> this(ref immutable typeof(this)) immutable;
> this(ref immutable typeof(this)) inout;
>
> // inout original
> this(ref inout typeof(this));
> this(ref inout typeof(this)) const;
> this(ref inout typeof(this)) immutable;
> this(ref inout typeof(this)) inout;
>
> // etc.
>
> So, whatever solution we come up with for helping the compiler
> identify move constructors, I hope we can apply it to copy
> constructors too.
My experience thus far has been that I've been forced to use inout
(potentially then casting away const to then do anything useful) and that
having more than one copy constructor falls flat on its face once you put
your type with a copy constructor inside any other type, because the
compiler fails to generate all of the necessary copy constructors and just
complains that inout doesn't work.
There are similar problems with the various function attributes which aren't
type qualifiers.
Razvan create a PR to try to improve that situation, but it hasn't gone
anywhere:
https://github.com/dlang/dmd/pull/16429
Really, it would be nice to be able to just templatize the copy constructor
and have all of the corresponding copy constructors generated properly in
any other types that have that type as member. The current state of things
strongly implies that copy constructors were implemented and tested only in
fairly simple situations. They're just too much of a mess in practice.
- Jonathan M Davis
More information about the Digitalmars-d
mailing list