Casting away const

Jonathan M Davis jmdavisprog at gmail.com
Mon Aug 9 14:15:41 PDT 2010


On Monday, August 09, 2010 07:13:31 Steven Schveighoffer wrote:
> Casting away const just to read the data is useless.  You can read const
> data without a cast.

That's not actually quite true. If all code were const-correct, then it would 
be, but much of D is not. For instance, toHash() is not const even though it 
should be. The result is that if you need to call it with a const object, you 
have to cast away the constness. No writing is going on there (unless the writer 
of the toHash() function in the derived class(es) screwed it up), but you can't 
call it with a const object. I've run into plenty of similar situations in C++ 
where whoever wrote the code didn't choose to use const at all, and it made 
making that code deal with const a royal pain if not totally unreasonable. 
Casting away constness in cases where you knew that no write was going to take 
place or just dropping the constness in in your code were the only two options.

If anything, my reaction would have been that the programmer has no business 
writing to anything that they cast away the constness of. Dealing with code 
which _could_ and _should_ be const but isn't is the only place that I've ever 
even considered casting away const.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list