Incomplete knowledge + all powerful casts = troubles

Steven Schveighoffer schveiguy at yahoo.com
Mon Sep 19 11:01:02 PDT 2011


On Mon, 19 Sep 2011 13:54:20 -0400, Trass3r <un at known.com> wrote:

>> Unfortunately now the code contains a small bug. The cast now converts  
>> const(int)->uint, and foo() will modify a const value, that gives  
>> undefined effects in D2.
>
> I get the point, but in this particular case it's not a real bug since  
> foo doesn't take it by ref.
> The int is copied anyways, no matter if the source is const or not.
>
> I'm not sure how the actual problem should be solved though...
>
>> const(int) x;
>> auto y = cast(uint)x;
>> static assert(is(typeof(y) == const(uint)));
>
> ...cause this doesn't look right either, cause it silently keeps the  
> const.
> Imagine x being unapparently const and you pass y to some function or  
> template that doesn't allow const.
> You get an abstruse error message and don't really know why it happened  
> cause you think y is just a uint.
>
> Maybe stripping away constness should be a special case that can't be  
> combined with a normal cast, i.e. only 'cast()' can do it.

The way it's done in C++, you cannot remove const without a C-style cast  
or a const_cast.  The above would simply be a compiler error (instead of  
silently doing what you didn't ask it to do).

-Steve


More information about the Digitalmars-d mailing list