On Sunday, 15 November 2015 at 14:21:18 UTC, Dicebot wrote:
For instance, this code compiles and runs just fine.

    void main()
    {
        auto i = new immutable int(5);
        assert(*i == 5);
        auto j = cast(int*)i;
        *j = 42;
        assert(*i == 42);
    }

AFAIK this is UB already (in practice), you will get different results depending on compiler and optimization flags.

Oh, it's definitely undefined behavior. As far as the compiler is concerned, casting away either const or immutable means that it's up to _you_ to uphold the guarantee that they won't be mutated (whereas the compiler can guarantee it as long as you don't cast away const or immutable).

My point is that there's nothing actually stopping you from doing it, and you don't necessarily get a segfault or any other obvious problems when you do it. So, if the language were changed so that casting away const and mutating was defined behavior (at least as long as the underlying object is actually mutable), the only thing protecting folks against not accidentally casting away const on an object that is actually immutable is themselves. There is no compiler help, and the program will not necessarily blow up when you screw it up. So, you run a very real risk of introducing very subtle bugs into your programs with regards to immutable objects when you cast away const and mutate - even if the language is changed so that that is well-defined when the object is actually mutable.

At least with @mutable as Andrei proposed it, the compiler would be able to guarantee that an immutable object wasn't treated as mutable, even if it then allowed const references to mutate objects in a limited manner. So, while we'd lose out on the guarantee that const references could never mutate objects, at least that mutation would be limited and controlled with some compiler guarantees left intact, whereas making it well-defined to cast away const and mutate would be throwing pretty much all of the guarantees out the window (on top of being very error-prone).

- Jonathan M Davis

Reply via email to