Transitive const sucks

Bruno Medeiros brunodomedeiros+spam at com.gmail
Wed Sep 12 17:49:38 PDT 2007


Walter Bright wrote:
> Janice Caron wrote:
>> So the function was declared const, because /conceptually/ it was.
>>
>> But the class had a mutable cache, declared with the C++ keyword 
>> "mutable"
>>
>> Transitivity would wreck that.
> 
> You're right in that transitive const does not support the notion of 
> "logical const" (which is the usual term for what you are referring to).
> 
> The problem with logical const, however, is it offers no semantic 
> guarantees. I pass a logical const reference around, and the underlying 
> data may or may not change. I have no guarantees one way or the other, 
> and even worse, I can't even tell this is happening. "I" here meaning 
> the compiler, and our hapless code auditor.
> 
> This just pulls the rug out from under:
> 
> 1) functional programming
> 2) multithreaded programming
> 3) having a tightly specified interface
> 
> It goes back to painting a stripe across your hips and calling it a 
> seatbelt.
> 
> Given this, it isn't any surprise that C++ is disastrously difficult to 
> write functional & multithreaded programs in, and C++ mutability is one 
> of the reasons why. In C++, you can write const this and const that and 
> it doesn't mean jack squat. Many experienced C++ programmers will tell 
> you that const is little more than a documentation aid.
> 
> In other words, you're quite right that transitive const totally wrecks 
> using const to specify logical constness. And that's a good thing <g>.

In the interest of this discussion, here's a very nice article regarding 
the topic of logical constness: http://www.ddj.com/cpp/184403892
(the fact that it mentions Walter is coincidence, the article is simply 
the first result I got when I googled for "logical constness")

Anyways, we now see that 'mutable' and logical constness is dangerous 
when one wants to do multi-threaded optimizations. However, since D is 
going to have several flavors of const (such as 'const', 'invariant' and 
also the 'pure' functions), why not allowing logical constness on some 
of these flavors, but disallow it in others.
Namely, we could allow logical constness in 'const' and 'invariant' 
data, that is, changing 'mutable' members of 'const' and 'invariant' 
data. Thus D would allow for the the use cases of logical constness. But 
on 'pure' functions, no changes whatsover would be allowed, even of 
'mutable' members, and so we could still be able to use the 'pure' 
construct to safely create multi-threaded an parallelization optimizations.
Would this be ok?

-- 
Bruno Medeiros - MSc in CS/E student
http://www.prowiki.org/wiki4d/wiki.cgi?BrunoMedeiros#D



More information about the Digitalmars-d mailing list