Logical const

Steven Schveighoffer schveiguy at yahoo.com
Mon Nov 29 11:38:39 PST 2010


On Mon, 29 Nov 2010 14:33:48 -0500, Walter Bright  
<newshound2 at digitalmars.com> wrote:

> Steven Schveighoffer wrote:
>>> In fact, "logical constness" is a fraud anyway because the underlying  
>>> data isn't constant at all, one is completely relying on convention.  
>>> There's nothing at all preventing a supposedly logical-const-correct  
>>> function from returning a different value every time it is called, and  
>>> no way for the compiler to detect this.
>>  This is complete BS.  logical const in C++ is not the same as what  
>> logical const in D would be.  The transitive guarantee is much more to  
>> credit for allowing optimizations and static analysis than the omission  
>> of mutable members.  How does the fact that an Object's monitor is  
>> mutable affect the optimizer?
>>  In fact, how can *any* const or immutable function be optimized any  
>> differently than a mutable function?  The only optimizations I can  
>> think of are for pure functions.  And a pure function with immutable  
>> becomes significantly less optimizable if some fields might be  
>> mutable.  Couple that with the fact that a class may define new mutable  
>> members, it would be impossible to statically prove whether a class is  
>> completely immutable or logically immutable.
>>  But it would be good enough to allow logically-const/immutable to be  
>> different than const/immutable.  The problem is that this severely  
>> complicates the const system.
>>  If you are going to argue this case, please do not use C++ as a straw  
>> man, it's not the same as D.
>
> I don't understand your comment. In C++ you can write:
>
> struct S
> {
>      mutable int m;
>
>      int getM() { m = rand(); return m; }
> };
>
> Where's the "logical const"? It returns a different value every time.  
> Logical const is not a feature of C++.

You missed a const decorator there.

But in any case, const (even the non-logical variety) does not guarantee  
purity.  Only pure functions do that (always return the same value for the  
same input)

Counter-example:

struct S
{
    int m;
    int getM() const {return rand();}
}

-Steve


More information about the Digitalmars-d mailing list