Struct copy constructor with inout

dhs dhs at email.com
Tue Nov 14 16:39:42 UTC 2023


On Tuesday, 14 November 2023 at 14:58:21 UTC, Paul Backus wrote:
>
> ```d
> struct S2
> {
>     int* p;
>     this(const int* p) const
>     {
>         // Ok - counts as initialization
>         this.p = p;
>     }
> }
>
> immutable int answer = 42;
>
> void main()
> {
>     S2 s2;
>     // If this were allowed to compile...
>     s2.__ctor(&answer);
>     // ...then this could happen
>     *s2.p = 12345;
> }
> ```

Thanks for this explanation, it all makes perfect sense.

Regarding implicit qualifier conversion: in my code, S2 has a 
copy constructor, so it takes a "ref inout S2" as input. Since 
the copy constructor is in itself qualified as inout, the 
implicit "this" parameter is "ref inout S2" too.

We then have "const(S2) s2;" and "S2 ss2 = s2;". The implicit 
qualifier conversions *for references* do not allow conversion 
from "ref const(S2)" to "ref S2", so I assume that the "inout" in 
the copy constructor translates to "const". In that case, the 
copy constructor creates a "const S2", not an S2.

Does this "const S2" then get implicitly converted to "S2", 
before being assigned to "ss2"? I tried adding an opAssign() to 
S2 - it's not getting called. So I'm not sure what is actually 
going on here.



More information about the Digitalmars-d-learn mailing list