Accidentally killing immutable is too easy in D (Was: cast()x - avalid expression?)

Nick Sabalausky a at a.a
Wed Jun 1 15:38:58 PDT 2011


"Jonathan M Davis" <jmdavisProg at gmx.com> wrote in message 
news:mailman.527.1306962732.14074.digitalmars-d at puremagic.com...
> On 2011-06-01 13:42, Nick Sabalausky wrote:
>>
>> It's nice in a way, but it's all based on the way cast handles modifiers.
>> And I've always been a bit unconfortable with how that's handled (In 
>> fact,
>> I was just thinking about this yesterday). Specifically, it seems
>> extremely bad that it's so incredibly easy to accidentaly cast away 
>> things
>> like const and immutable:
>>
>> For example, if I know I have an array of uint's, and I want to deal with
>> the individual bytes, it's perfectly safe and sensible to cast it to a
>> ubyte[] (a long as you factor in endianness, of course). So, you do
>> "cast(ubyte[])myArray". But, OOPS!!: If myArray happened to be immutable,
>> then merely trying to cast the type has inadvertantly cast-away 
>> immutable.
>> Not good! Casting away const/immutable really, really should have to be
>> explict.
>>
>> Of course, you can probably use some fancy helper templates to make sure
>> you preserve all modifiers. But needing to do so is just asking for
>> mistakes: it seems like a huge violation of "make the right way easy, and
>> the wrong way hard".
>
> You really shouldn't be casting much anyway. It's the sort of feature 
> where
> you're only supposed to use it when you know what you're doing when you 
> use
> it.

Well, when you're doing low-level stuff, type casting tends to be commonly 
needed. And also when dealing with OO class hierarchies. Problem is, like 
bearophile said, those uses are typically orthogonal to constness and 
immutability. It's nice that D's cast is multi-purpose, but I don't like 
that it's so easy to conflate the purposes of changing the modifiers and 
changing the base types since you're usually just trying to do one or the 
other.

If we can change *just* the modifier with cast(immutable), cast(const) and 
cast(), without touching the base type, then that's fantastic. Certainly 
very useful. But it's equally useful (maybe even more useful due to the 
severe danger of casting to/from immutable), to similarly have a way to 
change just the base type without touching the modifier. Both of these "just 
one or the other" forms should be the typical usage of cast in 99+% of 
cases.

> And if there's really any possibility that you're dealing with immutable,
> perhaps you should be casting to const rather than mutable. Personally, I 
> find
> how C++ created multiple types of cast (include const_cast) _highly_ 
> annoying
> and generally useless, and I'm _very_ glad that D didn't do anything of 
> the
> sort.
> 



More information about the Digitalmars-d mailing list