D not considered memory safe

Jonathan M Davis newsgroup.d at jmdavisprog.com
Wed Jul 17 18:37:54 UTC 2024


On Monday, July 15, 2024 12:21:24 PM MDT Walter Bright via Digitalmars-d 
wrote:
> On 7/11/2024 3:20 AM, Timon Gehr wrote:
> > The simple point remains that Steven is absolutely correct that putting
> > `@safe:` does not work.
>
> True, when the code is not @safe and needs fixin'.

It is the case more frequently than not that you do not want to mark
templated functions with @safe, and there is nothing about that that needs
fixing.

Most templated functions should be designed in a way that they work with
either @safe or @system depending on the template arguments, because you're
unnecessarily restricting the types or functions that can be used with the
template otherwise. Ideally, the templated function will be written in a way
that it will be @safe if all of the functions it's calling are @safe but not
require that any of them be @safe. Range-based code is a prime example of
this, because some ranges are @safe and some aren't, but code like
std.algorithm needs to work with them either way. If that templated code is
written properly, it will then be @safe if the range can be @safe, but if it
actually required @safe, then it wouldn't work with ranges that weren't
@safe. As such, for the majority of templated code, using @safe: is a
disaster and does not indicate that _anything_ needs fixing. Inference is
what's needed for the vast majority of templates.

Now, if you're writing a template that works on a specific subset of known
types (e.g. all integer types), then it becomes possible to use @safe
explicitly, because you know that what you're doing can be @safe for all of
the types that the templated function can be instantiated with, and it could
be considered a bug if the code didn't work with @safe:, but for many
templates, you need @safe to be inferred, and using @safe: causes nothing
but trouble.

In most cases, slapping : at the top of a module with any attribute causes
issues. It can even cause problems with stuff like public, since that can
easily result in a situation where you accidentally make imports public. In
general, : should be used with great caution with regards to attributes, and
in many cases, IMHO, it borders on being a code smell given how error-prone
it can be. It also becomes a problem with maintenance and code reviews,
because it's often not obvious that a particular attribute is in effect in a
section of the file when it was applied using :. So, using @safe: really is
not a solution for much of anything. It _can_ work in some cases, but I'd
strongly advise against it in general, because it will cause problems.

- Jonathan M Davis





More information about the Digitalmars-d mailing list