Logical const

Walter Bright newshound2 at digitalmars.com
Sun Nov 28 17:13:00 PST 2010


Peter Alexander wrote:
> On 28/11/10 9:35 PM, Walter Bright wrote:
>> You can write memoized functions in D, you just can't label them as
>> const. You'll be relying on convention. Memoized (logically const)
>> functions are not verifiable in C++, either, so you are not technically
>> worse off.
> 
> I am technically worse off, just not from the compilers point of view.
> 
> I see your point about C++ const being a convention, but that doesn't 
> change the fact that it is still very useful, even if it useless for the 
> compiler. If I give some const object to a function:
> 
> void render(const GameObject&);
> 
> GameObject obj;
> render(obj);
> 
> I can be sure that my object will come back unmodified.

Nope, for 5 reasons:

1. use of mutable

2. it's legal to cast away const and modify the data anyway

3. if your object is more than a simple value type, for example if it contains 
references, the const doesn't apply to them. In particular, if you use the PIMPL 
idiom, all your const's are worthless.

4. render() may have another mutable reference to that same obj

5. another thread may trash obj's contents at any moment

D offers compile time guarantees against 1,2,3, and 5. 4 can be covered if you 
use pure functions or immutable data.


> That it is the 
> primary purpose of const. Like you said, it allows you to reason about 
> your programs.
> 
> Yes, GameObject could be unreasonably mutilated by careless use of 
> mutable, but in practice that simply doesn't happen.

Sure, if you carefully follow the convention. The problem happens when you

a) make a mistake following the convention or
b) have to deal with other programmers who may not be so careful.

How would you know?


More information about the Digitalmars-d mailing list