Casting away const

Steven Schveighoffer schveiguy at yahoo.com
Mon Aug 9 15:01:28 PDT 2010


On Mon, 09 Aug 2010 17:15:41 -0400, Jonathan M Davis  
<jmdavisprog at gmail.com> wrote:

> 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.

Then the author failed to make it const, and it's a bug in the function  
definition.  "Casting away const if you don't write" is crap, and should  
be treated as suspiciously as code that writes to const data.

What if calculating the hash is expensive, and you know you don't have to  
recalculate it, you might cache it as a member of the class.  Believe me,  
if a programmer can do it, he will.  Documentation saying "don't do this!"  
isn't enough.

> 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 const in C++ and writing to the data I think is not  
undefined.  I believe that's one of Walter's gripes with C++ const.

-Steve


More information about the Digitalmars-d-learn mailing list