www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - how to write a const-object container array?

reply sn <some where.com> writes:
I want a container (array) which holds const-object, i.e. when someone get an
object out of this container, he cannot modify it using that reference.

NOTE: I don't want the container array itself to be const, I may insert or
remove object from that array.

I tried:

class A {}

int main() {
  const(A) ca[2];
  const a = new A();
  ca[0] = a;

  return 1;
}

$ dmd constarray.d
constarray.d(4): Error: slice ca[] is not mutable
constarray.d(6): Error: ca[0] isn't mutable
Mar 11 2008
parent "Steven Schveighoffer" <schveiguy yahoo.com> writes:
"sn" wrote
I want a container (array) which holds const-object, i.e. when someone get 
an
 object out of this container, he cannot modify it using that reference.

 NOTE: I don't want the container array itself to be const, I may insert or
 remove object from that array.

 I tried:

 class A {}

 int main() {
  const(A) ca[2];
  const a = new A();
  ca[0] = a;

  return 1;
 }

 $ dmd constarray.d
 constarray.d(4): Error: slice ca[] is not mutable
 constarray.d(6): Error: ca[0] isn't mutable

Unfortunately, because tail-const for class references doesn't exist, you cannot do this easily. There are two ways to do it now. first, you can use a dynamic array: const(A)[] ca; ca ~= new A; Note that you can't change elements that you have added without doing array concatenation, so to replace element 5 for instance you have to do: // replace ca[5] with element e ca = ca[0..5] ~ e ~ ca[6..$]; The other way is to have an array of tail-const pointers to classes, backed by heap-allocated references to classes: const(A)* ca[2]; // this is the easiest way I know how to allocate a class reference on the heap A[] tmp = new A[1]; tmp[0] = new A(); ca[0] = &tmp[0]; You can call methods directly on an element: ca[0].constMethod(); But you can't do comparisons or call the elements' operators if they are valid for pointer operations: ca[0]++; // will increment the pointer, not call A.opPostInc() *(ca[0])++; // this is what is required Yeah, it's ugly, and consumes lots of extra memory, but it's all we have to work with until Walter can come up with (or accept an existing proposal for) a way to have tail-const class references. -Steve
Mar 11 2008