Dynamically allocated Array mutable but non resizeable

Steven Schveighoffer schveiguy at gmail.com
Mon Jun 14 17:34:00 UTC 2021


On 6/14/21 11:09 AM, Jalil David Salamé Messina wrote:
> 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!

D doesn't have head-const. So you must hide the mutable implementation 
to get this to work.

You'd want to do this anyway, since you don't want to directly use the 
pointer for anything like indexing (it should first validate the index 
is valid, at least in an assert).

-Steve


More information about the Digitalmars-d-learn mailing list