Making array elements truly const/immutable

Ali Çehreli acehreli at yahoo.com
Thu Aug 2 02:25:01 PDT 2012


On 08/02/2012 01:55 AM, Joseph Rushton Wakeling wrote:

 > (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?

.dup and .idup will always make a copy, std.conv.to won't:

import std.conv;

void main()
{
     immutable(int)[] i = [ 1, 2 ];
     immutable(int)[] j = to!(immutable(int)[])(i);
     assert(i is j);
}

 > 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; }
 > }

'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.

 > ... but where it's guaranteed that no external agent can touch the
 > inside of _foo.

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.

Ali



More information about the Digitalmars-d-learn mailing list