Casting away const and invariant

Matti Niemenmaa see_signature at for.real.address
Sun Sep 9 07:51:50 PDT 2007


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. In D,
if you cast away const, no matter how, it is undefined behaviour, and something
you shouldn't do.

I can understand disallowing casting away const, and I'm fine with that. But
adding a mechanism specifically for that purpose (your "cast(!const)") is
something I don't think is a good idea, because it breaks one of the principles
on which D's new const semantics were built.

It appears that what you're actually after is for the compiler to be smarter
about catching errors which lead to undefined behaviour, which is fine. In this
case, you want a warning/error on casting from a const type to a non-const type.
But fact is, the DMD frontend isn't very good at such things, and probably won't
improve significantly any time soon.

-- 
E-mail address: matti.niemenmaa+news, domain is iki (DOT) fi



More information about the Digitalmars-d mailing list