Compiler generated opAssign

Christopher Winter christopher.winter at ahrefs.com
Fri Sep 1 17:46:33 UTC 2023


What does the compiler generated opAssign for a struct look like?

Let's say I have a struct, which has at least one `const` member.

```
struct S
{
     this(int some_a, int some_b)
     {
         a = some_a;
         b = some_b;
     }
     int a;
     const int b;
}
```

If I then try to assign to it, the compiler complains that struct 
instances with const members cannot be be modified.


```
     auto s = S(1, 2);
     s = S(3, 4);
```

Full example here: https://run.dlang.io/is/ssT12m

This makes sense to me if I understand the compiler to be 
generating a member-by-member assignment operator like in C++, 
but the description in Programming in D states that in D 
(Assignment Operator section 
[here](http://ddili.org/ders/d.en/special_functions.html)) the 
compiler generated function will create a temporary copy of the 
right-hand-side, and then replace the left-hand-side with that 
temporary copy. To me that description implies that const members 
should be ok when it comes to assigning to the entire object.

In my specific encounter with this scenario, I'm dealing with 
`core.stdcpp.string_view` so I can't modify the definition to 
remove the const member. Also with an old version of ldc I have 
on my linux machine this seems to work, though I'm not able to 
replicate that with the "all dmd versions" option on run.dlang.io 
(where they all fail to compile).


More information about the Digitalmars-d mailing list