www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Dynamically allocated Array mutable but non resizeable

reply Jalil David =?UTF-8?B?U2FsYW3DqQ==?= Messina <jalil.salame tum.de> writes:
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
parent reply Steven Schveighoffer <schveiguy gmail.com> writes:
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
parent Jalil David =?UTF-8?B?U2FsYW3DqQ==?= Messina <jalil.salame tum.de> writes:
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).

 -Steve
Seems like I'll have to have a look at operator overloading, thanks for the clarification!
Jun 15 2021