Article: Why Const Sucks

joe joe at example.com
Sun Mar 11 15:45:27 UTC 2018


On Thursday, 8 March 2018 at 15:13:09 UTC, Steven Schveighoffer 
wrote:
> On 3/8/18 9:58 AM, joe wrote:
>> On Monday, 5 March 2018 at 10:57:35 UTC, Jonathan M Davis 
>> wrote:
>>> Here's something I wrote up on const:
>>> /snip
>> 
>> May be not entirely related, but a little gotcha.
>> 
>> given:
>> 
>> interface XY {}
>> 
>> class Foo: XY {}
>> class Bar: XY {}
>> 
>> void doSomething(in XY sth)
>> {
>>    auto foo = cast(Foo)sth; // error in @safe code
>> }
>> 
>> But the compiler doesn't emit a warning that const got cast 
>> away in @system code.
>> Since @system is the default setting and casting const away is 
>> by definition undefined behavior, there should be some 
>> feedback.
>> 
>> If you cast away const in C++ you need to be explicit about it 
>> by using const_cast, documents the intention rather than D's 
>> swiss-army-cast.
>
> This is a problem with the cast system, not const. ...

I figured. Sorry for off topic.

> ... D has one cast mechanism, and it's used to:
>
> a) dynamic type cast
> b) hook user-supplied opCast
> c) enter undefined behavior by casting away const/immutable.
>
> I really think we should have a separate mechanism for a and b, 
> as they are far less dangerous than c.
>
> std.conv.to does this as well, ...

Thanks for pointing this out.

> ...but the language should have some safeguards against using 
> "safe casting" incorrectly.
>
> -Steve

yes, that's what I was aiming for :)

This one got me because I assumed, with all the improved security 
in place, D would never silently do such a thing...
Assumptions, right? ...the root of all evil. I should know 
better. haha.

Anyways, thanks for the insight and have a nice Sunday.


More information about the Digitalmars-d-announce mailing list