Dynamically allocated Array mutable but non resizeable
Jalil David Salamé Messina
jalil.salame at tum.de
Mon Jun 14 15:09:05 UTC 2021
I'm searching for a way to do something like this in D:
```cpp
struct MyStruct {
const size_t length;
int *const data;
MyStruct(size_t n) : length(n) {
data = new int[length];
}
}
```
This way it is mutable, but non resizeable:
```cpp
MyStruct s = MyStruct(10);
s.data[0] = 42; // Valid
s.data = new int[20]; // Error: assignment to const
```
Doing some extra reading about the theme I found the section on
[Type Qualifiers](https://dlang.org/spec/const3.html), which
makes me believe that the "tail constness" of D will disallow
this kind of behavior.
My solution would be overriding the `[]` to make MyStruct behave
as an array and hiding the implementation details, but if you
have a more elegant solution I'm all ears!
More information about the Digitalmars-d-learn
mailing list