cannot modify struct with immutable members
ted via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Fri Jan 2 22:10:14 PST 2015
ketmar via Digitalmars-d-learn wrote:
> On Sat, 03 Jan 2015 15:56:58 +1030
> ted via Digitalmars-d-learn <digitalmars-d-learn at puremagic.com> wrote:
>
>> Ironically, I'm trying to use const in an effort to understand it...but
>> there seems to be an unusual amount of pain until I grok it.
> just remember that `const` "infects" everything down to the bytes when
> it's applied. and it's forbidden to overwrite `const` vars with
> different values.
>
> in your canse it "infects" your `A` struct, effectively converting it
> to `const A` (with `const int someInt`). and as you can't change
> "consted" value, and structs are `memcpy()`ed... compiler tracked that
> down and refused to do it.
>
> so you don't really need `const` fields in D. you can make getters
> `const` though, so that they can be used on `const MyStruct` instances.
>
> so two rules should help you here:
> 1. it's forbidden to overwrite `const` vars with new values.
> 2. `const` will infect everything down to bytes.
>
> maybe this will help you like it helps me. ;-)
Thanks for your help....besides the issues that you pointed out, I had
forgotten that structs are always copied (I'm so used to thinking in
pointers (if you ignore the fubar from my earlier example) - and a world
where copying data structures is an expensive exercise to be
avoided).......
I'm now taking the view that const is there for the compiler to optimise
code on the basis that nothing can alter it once set (and can only be set
on initialisation). So I see your point that it would not be used very
often in general defensive code - better to provide access restrictions
(getters) for most cases.
I am refactoring the code to use getters/setters....
One of the really good things about D is that it is relatively painless to
refactor when you have to - much less boilerplate to have to move around !
thanks again,
regards,
ted
More information about the Digitalmars-d-learn
mailing list