@safe - why does this compile?

Timoses timosesu at gmail.com
Sat Jul 14 06:50:59 UTC 2018


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?


More information about the Digitalmars-d-learn mailing list