Casting away const
and modifying an element is undefined behavior in D. Don't do it. Once something is const
, it's const
. If the element of an array is const
, then it can't be changed. So, if you have const(A)[]
, then you can append elements to the array (since it's the elements that are const
, not the array itself), but you can't alter any of the elements in the array. It's the same with immutable
. For instance, string
is an alias for immutable(char)[]
, which is why you can append to a string
, but you can't alter any of its elements.
If you want an array of const
objects where you can alter the elements in the array, you need another level of indirection. In the case of structs, you could use a pointer:
const(S)*[] arr;
but that won't work with classes, because if C
is a class, then C*
points to a reference to a class object, not to the object itself. For classes, you need to do
Rebindable!(const C) arr;
Rebindable is in std.typecons.