On Tuesday, 16 February 2016 at 15:12:00 UTC, Ola Fosheim Grøstad wrote:
On Tuesday, 16 February 2016 at 15:10:40 UTC, Timon Gehr wrote:
Legal.

Ouch... :-/

const guarantees that the data will not be mutated via that reference to the data. It guarantees nothing about other references to that data. For that, you need immutable. But as long as const guarantees that the data can't be mutated via that reference, then there's plenty of code where the programmer can look at it and know for sure that that data isn't being mutated, because they know that the code in question can't have access to the same data via a mutable reference (the compiler can see that too, but in a much more limited fashion than a programmer is going to be able to know).

If casting away const and mutating is defined behavior, then you lose that guarantee, and instead of knowing that some code doesn't have access to a mutable reference to that data being enough, you have to actually know what the code does to know that it's not casting away const and mutating.

Having @mutable would be better than allowing casting away const and mutating to be defined behavior (at least when the underlying data is mutable rather than immutable), because it would at least restrict the data that can be mutated, and it would guarantee that you don't accidentally mutate an immutable variable (since it would make no sense to have a type with an @mutable member be immutable, whereas if you're casting away const, getting that right would be completely up to the programmer). But having @mutable would still mean that you can't rely on a const variable not being mutated when you pass it to a function that you know doesn't have access to a mutable reference to the same data. If you knew that no @mutable was involved, it would be the same as now, but you'd have to know for sure that @mutable was involved, and even if it isn't now, it could be later after refactoring.

So, having @mutable would be far better than having it be defined behavior to cast away const and mutate (assuming that the underlying data is mutable rather than immutable), but you're still losing out on guarantees that we have now. After all, most code isn't going to do the equivalent of

    // prototype f(const A *, A*);
    f(ptr,ptr);

Ultimately, I think that the question is whether the guarantees that we currently get with const are worth more or whether the idioms that don't work with const right now but would work with @mutable are worth more. But regardless, the guarantees provided by const obviously pale in comparison to the ones that immutable provides.

- Jonathan M Davis

Reply via email to