Struct copy constructor with inout

Steven Schveighoffer schveiguy at gmail.com
Tue Nov 14 13:41:32 UTC 2023


On Tuesday, 14 November 2023 at 08:50:34 UTC, dhs wrote:

> I am using following code:
>
> ```d
> struct S1
> {
>     this(ref const S1 s) const { writeln("copy"); }
>     int i;
> }
>
> struct S2
> {
>     this(ref inout S2 s) inout { writeln("copy"); }
>     int i;
> }
>
> void test()
> {
>     const(S1) s1;
>     S1 ss1 = s1; // error, ss1 not qualified as const
>
>     const(S2) s2;
>     S2 ss2 = s2; // fine, why?
> }
> ```
>
> Isn't "inout" supposed to copy the const-ness of its parameter 
> to the constructor's attribute? In other words: why doesn't 
> ss2=s2 fail here?


`ss2 = s2` does not fail because the type is implicitly 
convertible to non-const (a const int can be converted to a 
mutable int). Change `i` to `int *` and it will fail.

IMO, the first should succeed as well. And I will note that the 
error looks different from what you say:

```
Error: copy constructor `testinoutctor.S1.this(ref const(S1) s) 
const` is not callable using argument types `(const(S1))`
```

I'm not sure what this means. There shouldn't be a copy being 
made here, as the thing is already const. I don't understand this 
error, and it looks like a bug to me.

-Steve


More information about the Digitalmars-d-learn mailing list