About Immutable struct members and arrays.

anonymous via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Jan 6 16:19:12 PST 2016


On 06.01.2016 23:04, Jack Applegame wrote:
> import std.algorithm;
>
> struct Bar {
>      const int a;
>      int b;
> }
>
> void main() {
>      Bar[1] arr;
>      Bar bar = Bar(1, 2);
>      bar[0].b = 4;

Assuming you meant `arr[0].b = 4;`. Just overwriting the mutable part of 
bar[0] is ok, of course.

>      move(bar, arr[0]);       // ok

I consider it a bug that this compiles. You're overwriting immutable 
data, which shouldn't be possible (without casting). 
https://issues.dlang.org/show_bug.cgi?id=15315

>      arr[1] = bar;            // fail, why?

Assuming you meant `arr[0] = bar;`.

The error message isn't too bad here: "Error: cannot modify struct 
arr[0] Bar with immutable members". You're trying to overwrite immutable 
data, that's not allowed.

>      move(Bar(1, 2), arr[0]); // fail, why source parameter isn't auto ref?

I'm not sure about the details. Maybe it would make sense for `move` to 
accept rvalues, maybe not. Breaking immutable is certainly not a good 
reason to do it, though.

> }


More information about the Digitalmars-d-learn mailing list