Making array elements truly const/immutable
Joseph Rushton Wakeling
joseph.wakeling at webdrake.net
Thu Aug 2 04:42:10 PDT 2012
On 02/08/12 10:25, Ali Çehreli wrote:
> .dup and .idup will always make a copy, std.conv.to won't:
Brilliant. You could actually say that my _real_ problem was how to copy
const(int)[] to int[] without the cast, as it's the cast that brings the lack of
safety. std.conv.to seems to fit the bill perfectly.
> 'const' is a better choice there:
>
> @property const(int)[] foo() { return _foo; }
>
> You don't want to give the misleading promise that the data is immutable, as the
> caller may treat it as such and store for future use or freely pass to others
> threads.
Very good point. It's too easy for me to forget this key difference between
const and immutable.
> An intermediate type can reduce the chances of that happening, but it is not
> possible to prevent every potentially bad access in a system language like D.
Sure. What I'm looking for is not some absolute and unachievable prohibition,
but a safety-checking mechanism that would be flagged by the compiler. The real
problem was that I couldn't just set bar = foo without bar being const, but
didn't know how to do this without the cast, which violates safety.
Since to!()() allows me to make that copy -- or is it copy-on-write? -- in a
safe way, that seems a perfectly viable solution.
More information about the Digitalmars-d-learn
mailing list