Is opCast need, we have to!

Brad Roberts braddr at puremagic.com
Thu Dec 2 11:05:31 PST 2010


On 12/2/2010 10:35 AM, Jonathan M Davis wrote:
> On Thursday, December 02, 2010 02:23:23 foobar wrote:
>> My suggestion is much simpler than c++.
>> the _language_ needs only to provide two operators:
>> down cast operator and const cast operator.
>> interpret cast is a corner case that can also be implemented as a library
>> utility. conversions can and should be done with regular D code
>> (functions). which is not far from current D idioms (to!).
> 
> Personally, I think that const_cast is _the_ most pointless cast operator of the 
> lot. Simply cast, and if const is part of the new type and wasn't part of the 
> old one, then it's adding const-ness. If const isn't part of the new type and it 
> was part of the old one, then it's removing constness. Adding the extra 
> complexity just to make sure that you didn't accidentally add or remove const 
> seems to be totally overkill to me. And since casting away const in D is 
> technically undefined behavior anyway, does it even make sense to add a specific 
> operator for it?
> 
> - Jonathan M Davis

The problem is that it's unsafe across type changes.  Consider:

  const T x;
  void foo(T);
  foo(cast(T)x);  // drop const, it happens to be safe for some reason

What happens when the type of x changes?  Finding all casts of x across all the
code that might reference x is problematic.  When all you want to do is
manipulate the constness, being forced to do so via repeating the type means
your code is more fragile than it needs to be.

Later,
Brad


More information about the Digitalmars-d mailing list