On Sunday, 15 November 2015 at 15:20:24 UTC, Dicebot wrote:
On Sunday, 15 November 2015 at 15:09:25 UTC, Jonathan M Davis wrote:
After the call to bar, the compiler can guarantee that the value of foo has not changed, because it's not possible for bar to access foo except via a const reference, and it can clearly see that, because it can see that it's not possible for bar to access foo except via the reference that's passed to it.

Note that it can only do so if escape analysis is able to prove no other reference escapes to the same data. Otherwise it can be mutated even during that function call in other thread.

Except that shared isn't involved here. The objects are thread-local, so other threads don't matter. The combination of TLS and pure does make it so that the compiler could theoretically do optimizations based on const. immutable is not actually required, though it obviously provides far better guarantees.

However, even with full-on escape analysis, the compiler is pretty limited in where it can guarantee that a const object isn't mutated by another reference. So, it really doesn't mean much. But my point was that there _are_ cases when the compiler can do optimizations based on const without immutable being involved, even if they're rare.

All together it makes benefits of such deduction absolutely not worth UB limitation in my opinion.

The primary benefit of making it undefined behavior to cast away const and mutate is that then you actually have the guarantee that an object will not be mutated via a const reference. You get actual, physical const. As long as there's a backdoor out of const, const provides no real guarantees. Rather, it just prevents accidental mutation and serves as documentation for which functions are supposed to be able to mutate the logical state on of an object - which is why (as I understand it at least) Walter has typically argued that C++'s const is useless.

Now, given how incredibly limiting physical const is, maybe we should be more lax with D's const, but if we are, we lose out on the compiler guarantees that we currently get and basically end up with a transitive version of C++'s const (except that we have the added risk of mutating an immutable object if we're not careful).

- Jonathan M Davis

Reply via email to