On Tuesday, May 01, 2012 23:48:29 Mehrdad wrote: > In the world of OOP, when would "guarantee"ing (so to speak) 'physical' > const-ness ever be handy? > > Wouldn't "physical" const-ness be an implementation detail of the object, > and therefore, impossible to determine by the user of the object?
No, it's not an implementation detail. When you mark an object as being physically const, then you're guaranteeing that you will not alter it through that reference or pointer (and not at all, if it's a value type, because then there can't be another reference or pointer which mutates it). The type system guarantees this, because it disallows any const variable from being mutated. When dealing with a const object, you can only call const functions on its interface. Whatever implementation there is for those interface methods would also have to be const to implement that interface. And the type system would then disallow any non-const functions being called within the implementations of those functions as well as disallowing the mutation of member variables. So, the type system guarantees that the object will not be mutated at all by any const function. And since const is part of the interface of the object, it is very much _not_ an implementation detail. Physical constness is _required_ in order to have immutable ever be converted to const, because immutable objects can _never_ be mutated through _any_ reference or pointer. If D's const were not transitive as well as guarantee that any const reference cannot alter the object it points to, then you couldn't have immutable be convertible to const, because const would not protect it against mutation. So, C++'s const is impossible in D if immutable is going to be convertible to const. It's _logical_ constness that is near-impossible to have the compiler verify, because it has no way of determining that the variables that you mark as mutable or from which you cast away const and mutate don't affect the logical state of the object. _You_ may know, but the compiler can't determine that. - Jonathan M Davis
