Casting away const and invariant

Matti Niemenmaa see_signature at for.real.address
Sun Sep 9 06:18:47 PDT 2007


Janice Caron wrote:
> I've noticed that you can do this in D2.0, without knowing the type of p.
> 
> auto q = cast(const) p;
> 
> The type of q is now the type of p, but with added constness. However,
> if you want to take the constness away, you must explicitly specify
> the full type, as in:
> 
> auto r = cast(int *) q;
> 
> Seems to me, this is a good place for coding errors to creep in, and
> it's the exact reason that const_cast<> was introduced into C++. So,
> how about allowing
> 
> auto r = cast(!const) q; /* currently will not compile */
> 
> which would eliminate that sort of error.

Casting away const leads to undefined behaviour and should not be done. In
general, whenever you cast anything, you need to look carefully at exactly what
it is you're casting from, to, and why.

The whole reason why C++'s const is completely useless for optimization purposes
is that you can cast it away at any time. One goal of D const was to allow
optimization.

Read the arguments against C++'s const here and think carefully about whether
you really want a const_cast in D: http://www.digitalmars.com/d/const.html

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



More information about the Digitalmars-d mailing list