D const design rationale
Sean Kelly
sean at f4.ca
Fri Jun 22 12:29:46 PDT 2007
Walter Bright wrote:
> Sean Kelly wrote:
>> Walter Bright wrote:
>>> In C++, sometimes const means invariant, and sometimes it means
>>> readonly view. I've found even C++ experts who don't know how it works.
>> Odd. The C++ system always seemed extremely simple to me.
>
> It isn't. I run into people all the time who are amazed to discover that
> const references can change. Few understand when const is invariant and
> when it isn't. I've never even seen anyone mention the problem where the
> non-transitive const destroys any hope of having FP like capabilities in
> C++.
Matter of opinion, I suppose. The C++ design was immediately clear to
me, though it obviously wasn't for others. I grant that the aliasing
problem can be confusing, but I feel that it is a peripheral issue.
>> I personally find the use of three keywords to represent three
>> overlapping facets of const behavior to be very confusing, and am
>> concerned about trying to explain it to novice programmers. With
>> three keywords, there are six possible combinations:
>>
>> final
>> const invariant
>> final const
>> final invariant
>> const invariant
>> final const invariant
>
> Probably the thing to do is simply outlaw using more than one.
If nothing else, I imagine "final const" will be a necessary combination.
>> That some of these may be redundant just serves to further confuse the
>> issue in my opinion. So I wondered whether one of the keywords could
>> be done away with. Previously, you said 'invariant' may only apply to
>> data whose value can be determined at compile-time, thus I imagine it
>> can only apply to concrete/data types (ie. not classes). Assuming
>> this is true, I wonder whether there is truly a point in having
>> 'invariant' at all. Assuming it were done away with, the system
>> becomes much simpler to me:
>>
>> final
>> const
>> final const
>>
>> And that's it. 'final' means a reference cannot be rebound, 'const'
>> means the data cannot be altered (through the reference), and 'final
>> const' means that both the reference is frozen and the data cannot be
>> changed. And that's it.
>
> It's missing the transitive nature of invariant.
How so? Given the above, I would consider 'const' to apply to a
declaration left-to-right and 'final' to apply to a declaration
right-to-left. If there are parenthesis, the rightmost (ie. closing)
paren would effectively be the barrier between const and final. Thus,
from your example:
const (int**)* x;
Represents a mutable pointer to a const**, and:
final const (int**)* x;
Represents an immutable (ie. final) pointer to a const int**. By
default, both qualifiers would be fully transitive, so:
final int** x;
Would be an immutable pointer to an immutable pointer to a mutable int.
Or am I missing something?
Sean
More information about the Digitalmars-d
mailing list