Logical const

Walter Bright newshound2 at digitalmars.com
Wed Dec 1 15:34:34 PST 2010


Steven Schveighoffer wrote:
> If I see a function like:
> 
> void foo(const(C) c);
> 
> it doesn't mean that foo cannot modify the object referred to by c, it 
> just means that foo won't modify data referenced through c.  But a C 
> could store some data in a global variable, possibly even uniquely 
> associated with each instance (I have shown this in a very old post 
> proving logical const == const).  Then logically, the author of C could 
> consider that data a part of C.  I have no way to stop him from editing 
> that logical part of C, I'm relying on the author of C not to count 
> mutable state as part of the state of C.
> 
> Adding logical const just provides a location in the object itself for 
> this data that is not supposed to be part of C's state.  It's not 
> changing the guarantees that const already provides (which is very 
> little, but helps you follow the correct conventions).

foo() could only modify c if it has, via some other means, acquired a mutable 
reference to c. If the user does not provide this other mutable reference, then 
foo() cannot modify c. foo() cannot go out and grab or create such a reference.

This is quite the opposite from what you're proposing. Currently, the user has 
to make it possible for foo() to modify c, whereas your proposal is that foo() 
can modify c despite all attempts by the user to stop it.

Furthermore, if you mark foo() as pure, the compiler can guarantee there is no 
such hidden mutable reference.


More information about the Digitalmars-d mailing list