Thread overview
copying const
Jun 24, 2015
Freddy
Jun 24, 2015
Adam D. Ruppe
Jun 25, 2015
Jonathan M Davis
June 24, 2015
I was surprised when this happened, is it a bug or a feature?

---
struct A
{
    const int var;
}

int test()
{
    auto b = A(5);
    auto c = A(7);
    pragma(msg, typeof(b)); //A
    pragma(msg, typeof(c)); //A
    auto d = b; //compiles
    b = c; //doesn't compile
}
---
$ rdmd -main -unittest test
A
A
test.d(13): Error: cannot modify struct b A with immutable members
Failed: ["dmd", "-main", "-unittest", "-v", "-o-", "test.d", "-I."]
June 24, 2015
On Wednesday, 24 June 2015 at 19:41:54 UTC, Freddy wrote:
> I was surprised when this happened, is it a bug or a feature?

Feature, overwriting const or immutable data would violate the promise that it never changes. Saving a struct over another struct is just another way of overwriting the data.
June 25, 2015
On Wednesday, 24 June 2015 at 19:45:12 UTC, Adam D. Ruppe wrote:
> On Wednesday, 24 June 2015 at 19:41:54 UTC, Freddy wrote:
>> I was surprised when this happened, is it a bug or a feature?
>
> Feature, overwriting const or immutable data would violate the promise that it never changes. Saving a struct over another struct is just another way of overwriting the data.

This is why you should almost never have structs with const or immutable members. It's overly limiting. Once one member is const or immutable, the whole thing might as well be, and if that's what you want, just declare the variable const or immutable and don't have individual members be const or immutable. If read-only is what you're looking for, then wrap it in an @property function which returns the value but don't provide a corresponding setter property, and then the only way to overwrite it is to assign a value to the entire struct.

Classes are different, since they're reference types, but with structs, I'm not sure I've ever seen a case where I thought that it was a good idea to have any of its members be const or immutable.

- Jonathan M Davis