Inout-parameter - replace one const-handle with another

In the object, I have a const-handle array for some object of another specific class. In the method, I can return one of these descriptors as an inout parameter. Here as a simplified example:

 class A {} class B { const(A) a[]; this() { a = [new A(), new A(), new A()]; } void assign_const(const(A)* value) const { // *value = a[0]; // fails with: Error: cannot modify const expression *value } } void main() { const(A) a; B b = new B(); b.assign_const(&a); assert(a == ba[0]); // fails .. obviously } 

I do not want to remove const in the original array. Class B means as some kind of constant on collection A I am new to D coming with C ++. Am I messed up with const-correctness in the D-way? I tried several ways to make this work, but I don’t know how to do it right.

What is the correct way to perform this search without an β€œevil” caste?

+4
source share
1 answer

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.

+5
source

All Articles