Article: Why Const Sucks
Steven Schveighoffer
schveiguy at yahoo.com
Thu Mar 8 15:13:09 UTC 2018
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. 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, but the language should have some
safeguards against using "safe casting" incorrectly.
-Steve
More information about the Digitalmars-d-announce
mailing list