@safe by default

Jonathan M Davis newsgroup.d at jmdavisprog.com
Sat Jun 16 17:46:56 UTC 2018


On Saturday, June 16, 2018 14:02:36 Jacob Shtokolov via Digitalmars-d wrote:
> On Saturday, 16 June 2018 at 13:57:48 UTC, Bastiaan Veelo wrote:
> > On Saturday, 16 June 2018 at 13:52:37 UTC, Jacob Shtokolov
> >
> > wrote:
> >> Is it possible to introduce a new parameter/flag to the
> >> compiler, to force all functions be @safe by default on a
> >> per-module basis?
> >>
> >> For example:
> >>
> >> ```
> >> module mymodule;
> >>
> >> pragma(safe);
> >
> > We already have that, and with even shorter syntax:
> >
> > ```
> > module mymodule;
> >
> > @safe:
> >
> > [...]
> > ```
> >
> > :-)
>
> OMG! Didn't know that! xD
>
> Thank you Bastiaan!

I would point out that in general, doing that with attributes is rather
error-prone, because it's easy for folks reading the code to miss them,
making it unclear that they're in effect, and because unfortunately most
attributes cannot be reversed, mass-applying them like that can then cause
problems down the line when you need the attribute to _not_ apply to a
function.

That being said, @safe is pretty much the one with the least problems,
because it's one of the ones that you can reverse by using @system or
@trusted explicitly where needed. However, there is no way to turn attribute
inferrence back on, so putting @safe at the top of a module that has
templated functions where the @safeness really needs to be inferred based on
the template arguments can be a problem (though it's not as big a problem as
putting @trusted at the top of the module, since at least with @safe, it
just means that you'd end up with templates that don't compile when they
would have been inferred as @system, whereas with @trusted, you'd
potentially be hiding memory-safety bugs).

So, while putting @safe at the top of the module may very well be your best
choice, be aware that mass-applying attributes like that _can_ cause
problems.

- Jonathan M Davis



More information about the Digitalmars-d mailing list