C++ mutable in D

Steven Schveighoffer schveiguy at gmail.com
Tue Aug 3 01:11:15 UTC 2021


On 8/1/21 2:21 PM, Michael Galuza wrote:
> On Friday, 30 July 2021 at 19:17:55 UTC, Michael Galuza wrote:
>> Is there any analogue of C++ `mutable` in D? As far as I understand, 
>> this is impossible due to transitive constness, but maybe some 
>> variation of `Rebindable` will be useful?
>>
>> P.S. Of course I mean 'fair' mutable, not qualifier-away `cast()`.
> 
> Let's slightly reformulate my question. Can we write in D smth like this:
> ```
> struct Mutable(T) { /* magic */ }
> 
> struct Shape {
>      private Mutable!double area;
> 
>      double getArea() const {
>          if (area == 0) { area = computeArea(); }
>          return area;
>      }
> }
> ```
> 
> In other words, can we implement method `void S.opAssign(T value) const` 
> of some struct `S` which change internal state of `S` and this method 
> doesn't have UB and doesn't break D's type system.

Yes. You need to use global space to do it.

e.g.:

```d

struct Shape {
    private static double[size_t] areaLookup;
    private const size_t magicNumber; // set on constructor
    double getArea() const {
       return areaLookup.require(magicNumber, computeArea());
    }
}
```

I've argued in the past that since this is possible, putting the memory 
inside (or along-side) the instance isn't all that different, and there 
are surely other typesystem-allowable ways (I think there was a plan at 
some point to use affixAllocator to do something like this). But 
"possible" here is not exactly equivalent to "desirable". What you need 
is some way to clarify that the "mutable" data is not actually part of 
the instance, but some nebulous region that is carried along with it.

-Steve


More information about the Digitalmars-d mailing list