@safe - why does this compile?

Dukc ajieskola at gmail.com
Fri Jul 13 22:17:59 UTC 2018


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.


More information about the Digitalmars-d-learn mailing list