Dropping const and modifying an element is undefined behavior in D. Don't do this. Once something is const , it is const . If the element of the array is const , then it cannot be changed. So, if you have const(A)[] , you can add elements to the array (since these are const elements, not the array itself), but you cannot change any of the elements in the array. Same thing with immutable . For example, string is an alias for immutable(char)[] , so you can add it to string , but you cannot change any of its elements.
If you need an array of const objects, where you can change the elements in the array, you need another level of indirection. In the case of structures, you can use a pointer:
const(S)*[] arr;
but this will not work with classes, because if C is a class, then C* points to a reference to the class object, and not to the object itself. For classes you need to do
Rebindable!(const C) arr;
Rebindable is in std.typecons.
source share