digitalmars.D.learn - Dynamically allocated Array mutable but non resizeable
- Jalil David =?UTF-8?B?U2FsYW3DqQ==?= Messina (23/23) Jun 14 2021 I'm searching for a way to do something like this in D:
- Steven Schveighoffer (7/34) Jun 14 2021 D doesn't have head-const. So you must hide the mutable implementation
- Jalil David =?UTF-8?B?U2FsYW3DqQ==?= Messina (4/10) Jun 15 2021 Seems like I'll have to have a look at operator overloading,
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!
Jun 14 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
Jun 14 2021
On Monday, 14 June 2021 at 17:34:00 UTC, Steven Schveighoffer wrote: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). -SteveSeems like I'll have to have a look at operator overloading, thanks for the clarification!
Jun 15 2021