@safe - why does this compile?
Steven Schveighoffer
schveiguy at gmail.com
Sun Jul 15 01:33:47 UTC 2018
On 7/14/18 2:50 AM, Timoses wrote:
> On Friday, 13 July 2018 at 22:17:59 UTC, Dukc wrote:
>> On Friday, 13 July 2018 at 13:52:27 UTC, Timoses wrote:
>>> I suppose this is another good example of how casting can be dangerous?
>>>
>>> E.g. also:
>>>
>>> immutable int i = 3;
>>> int* j = cast(int*)&i;
>>> assert(i == 3);
>>> *j = 4;
>>> assert(j == &i); // data occupies same address space
>>> assert(i == 3 && *j == 4); // yet the values differ
>>
>> No, casting classes to their subclasses is not dangerous to program
>> integrity, because it is checked. It is just a regular bug that
>> terminates the program when encountered.
>>
>> But casting away immutable can break program integrity as your example
>> demonstrates. For that reason the compiler won't let you do that if
>> you wrap that code in @safe, unlike the class cast.
>
> Thanks for the explanation. Only read the function safety chapter in
> depth after posting this : D.
>
> Still, is `cast`ing seen as something "dangerous" or as something that
> should only be done as a last resort? Should std.conv : to be prioritized?
Well, std.conv.to is going to throw if it doesn't dynamically convert.
So it depends on the behavior you want. But yeah, if you know it's going
to work, you probably want to do std.conv.to, it's safer.
Just FYI, it's kind of bad that you have to use cast here, because cast
isn't going to distinguish between dynamic casting and const casting.
It's kind of a problem in D in general. We don't have C++ niceties like
const_cast etc.
-Steve
More information about the Digitalmars-d-learn
mailing list