Casting away const and invariant

James Dennett jdennett at acm.org
Sun Sep 9 13:14:53 PDT 2007


Matti Niemenmaa wrote:
> Janice Caron wrote:
>> Actually, forget the specific example. What I'm getting at is that,
>> right now, it's possible to cast away const /accidentally/.
>>
>> My change would ensure that that was no longer the case.
>>
>> And you miss one of the major points about C++'s const_cast<>. Yes, we
>> all agree that it's a BAD THING to do. But the point about C++'s
>> const_cast<> is not that it will make constness go away, it's that
>> static_cast<> /won't/.
> 
> The major point about C++'s const_cast<> is that it is defined behaviour.

Only if the underlying object was not declared const in
the first place.  (This is also a point that Walter generally
elides when he critizes C++ const as not being useful for
optimization, and he coins the term "storage class" to apply
to those uses of const in C++ which *do* permit optimization,
though const is not a storage class in C++ terminology.)

If casting away const in D always involves undefined behavior
(and not only when the resulting object is modified) then it
should certainly be detected and disallowed at compile time.

-- James



More information about the Digitalmars-d mailing list