Why do "const inout" and "const inout shared" exist?

via Digitalmars-d digitalmars-d at puremagic.com
Mon Jul 3 08:48:26 PDT 2017


On Monday, 3 July 2017 at 07:22:08 UTC, Ola Fosheim Grøstad wrote:
> On Monday, 3 July 2017 at 01:15:47 UTC, Walter Bright wrote:
>> D const is different in that the compiler is allowed to 
>> generate code as if const was never cast to immutable. Such 
>> casts are also not allowed in @safe code.
>
> You probably meant mutable, but how does that bring any 
> advantages if any other thread can mutate it?

Unlike C++, in D objects can't be shared across threads, unless 
they are marked as `shared` (modulo un-`@safe` code - like casts 
and `__gshared` - and compiler bugs).
I.e. non-`shared` objects can't be mutated by more than one 
thread.
Combined with `pure` functions, the guarantees provided by D's 
type system are quite useful:

```
void main()
{
     int x = globalArray.foo();
}

// module-level non-shared variables are thread-local
int[] globalArray = [1, 2, 3, 4];

int foo(const(int)[] array) pure
{
     // globalArray[0] = 42; doesn't compile
     // For all intents and purposes, the elements of `array` can
     // be viewed as immutable here and they are *not* aliased.

     // ...
}
```

> Seems like you would want something closer to Pony's or Rust's 
> type system to gain any real benefits in terms of optimization.

I've watched a presentation on Pony's type system and it is 
indeed interesting,
but can you explain exactly what part of Rust's type system 
provides extra
benefits in terms of optimization over D's type system?


More information about the Digitalmars-d mailing list