Making array elements truly const/immutable

Era Scarecrow rtcvb32 at yahoo.com
Thu Aug 2 02:22:21 PDT 2012


On Thursday, 2 August 2012 at 08:56:42 UTC, Joseph Rushton 
Wakeling wrote:
> But, 2 questions: (I) is there a way to Mark an array as "under 
> no circumstances allow anything to modify the contents" in a 
> way that _can't_ be cast away like this? and (ii) given that I 
> can use instead bar = foo.dup to copy foo, is this guaranteed 
> to produce a _copy_ or is it smart inasmuch as the compiler 
> will check if bar is actually mutated and so only create a 
> duplicate if needed?

  If someone wants to modify something, they can go into assembly 
language and force it or use C wrappers that lie wouldn't stop 
it. Comes down to the programmers in the end.

> The motivation is that I want to have a class which contains a 
> dynamic array as a private member variable, but which is 
> readable through a class property.  I.e. something like
>
>     class Foo
>     {
>         private int[] _foo;
>         @property immutable(int)[] foo { return _foo; }
>     }
>
> ... but where it's guaranteed that no external agent can touch 
> the inside of _foo.  So, yes, I could return _foo.idup, but I'd 
> like to be able to guarantee that extra arrays won't be 
> allocated unless strictly necessary.

  I would thing the returned property would be dup'ed (since 
immutable cannot be const, since const says 'I won't change' and 
immutable is 'I can't change') and that problem goes away. If you 
returned const(int)[], then it may return the array pointer but 
the calling function (and others) shouldn't be able to modify it.

  It almost sounds like you'd want const access with COW-like 
properties (copy-on-write), so if you try to make changes it 
duplicates it and uses the duplicate afterwards. I began a test 
for COW arrays before, but haven't finished it.


More information about the Digitalmars-d-learn mailing list