Both safe and wrong?

Jonathan M Davis newsgroup.d at jmdavisprog.com
Fri Feb 8 08:31:26 UTC 2019


On Friday, February 8, 2019 1:02:59 AM MST ag0aep6g via Digitalmars-d wrote:
> On 07.02.19 23:33, Luís Marques wrote:
> > You are discussing evaluating the safety to the variable. Why not
> > evaluate the safety of the variable's initialization expression? That
> > is, @safe would always refer to code, just not necessarily functions.
>
> Evaluating the safety of initializers without somehow marking the
> variables as @safe/@system would fix the issue you brought up, but not
> the one that Olivier is talking about.
>
> His point is that you would still have to check manually if the globals
> you're using are safe or not. The compiler wouldn't see a difference
> between a safely initialized global and an unsafely initialized one.
>
> But @safe is supposed to eliminate that kind of manual verification.
>
> ----
> @safe:
> int* x = /* ... this initializer would be checked for safety ... */;
> void main()
> {
>      *x = 7; /* Guaranteed to be safe. */
>      *y = 7; /* Might exhibit undefined behavior. */
> }
> @system:
> int* y = /* ... this initializer would not be checked ... */;
> ----
>
> If we'd apply the attributes to the variables, and forbid using @system
> variables in @safe code, then `*y = 7;` would be rejected.

Except that there's no such thing as an @safe or @system variable. You're
talking about the exact same problem as when you have an @safe function
which takes a pointer, and you give it a pointer to invalid memory. @safety
depends on you giving valid input to @safe functions. So, if you have an
@safe function using a module-level variable whose initializer isn't @safe,
and it does something which makes that module-level variable unsafe to use,
then you're giving the function invalid input, just like if you passed it an
invalid pointer via one of its explicit parameters.

- Jonathan M Davis






More information about the Digitalmars-d mailing list