copying const

Jonathan M Davis via Digitalmars-d digitalmars-d at puremagic.com
Wed Jun 24 20:29:10 PDT 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


More information about the Digitalmars-d mailing list