I do not understand copy constructors

Steven Schveighoffer schveiguy at gmail.com
Fri Aug 13 21:34:29 UTC 2021


On 8/13/21 4:58 PM, Paul Backus wrote:
> On Friday, 13 August 2021 at 15:26:15 UTC, Steven Schveighoffer wrote:
>> The issue is that you can't convert const (or immutable or mutable) to 
>> inout implicitly, and the member variable is inout inside an inout 
>> constructor. Therefore, there's no viable copy constructor to call for 
>> the member, and the outer copy constructor cannot be generated.
> 
> I'm not quite sure I follow this. Are you saying that the constructor 
> call is typechecked as if it were written like this:
> 
> ```d
> this.field = this.field.__ctor(rhs.field);
> ```
> 
> ...and not like this?
> 
> ```d
> this.field.__ctor(rhs.field);
> ```
> 
> Because I can see how the first version would involve an const-to-inout 
> conversion, but the second version looks like it ought to work.

My point was just that `ref inout` normally binds to `ref const`.

Example:

```d
void foo(ref const int a)
{
   writeln("hi, a is ", a);
}

void bar(ref inout int b)
{
    foo(b); // fine
}
```

You implied in your statement that it was the ref-ness that prevents the 
call. Your simplified example was also a bit off, it was a double 
indirection of a ref array (which is definitely forbidden to be implicit 
cast).

But for constructors it's not the same. Essentially because constructors 
have different rules for what they can do with their inputs (the inout 
`this` parameter can be assigned to for the member's first assignment).

What I was trying to say (poorly) is that inside the inout copy ctor, 
you can actually call the const `A` copy constructor with an input of 
the other `inout A`. You just can't call it on the member (or assign it 
to the member), because that would allow some bad things to happen in 
some cases.

-Steve


More information about the Digitalmars-d-learn mailing list