Both safe and wrong?
ag0aep6g
anonymous at example.com
Mon Feb 4 00:18:48 UTC 2019
On 04.02.19 00:48, Luís Marques wrote:
> import std.stdio;
>
> @safe:
>
> const x = 42;
> int* y = cast(int*) &x;
>
> void main()
> {
> *y = 7;
> writeln(x); // prints 42
> }
>
> I'm probably too out of touch of how the safe type system should work,
> but this seems inconsistent. I would expect *either*:
>
> 1) Overriding x's const is unsafe and undefined behavior. The cast
> inside a safe block should cause an error. The 42 is fine.
>
> 2) As we promised the type system, we didn't modify the 42 through a
> const view of that value (x), instead we used a mutable view (y). The
> cast is fine. It should print 7 instead.
The thing here is that the @safe attribute only applies to functions.
`int* y = cast(int*) &x;` is not a function declaration, so `@safe:` has
no effect on it.
All code that's not in a function is @system, always. There is no way to
mark it as @safe.
More information about the Digitalmars-d
mailing list