D Article: Memory Safety
H. S. Teoh via Digitalmars-d-announce
digitalmars-d-announce at puremagic.com
Wed Jan 20 11:55:45 PST 2016
On Wed, Jan 20, 2016 at 07:25:43PM +0000, Dicebot via Digitalmars-d-announce wrote:
> `auto p = () @trusted { return &t; } ();`
>
> Huh, I thought Andrei was opposed to this idiom? Is it now considered
> reserved for templates or something has changed?
Yeah, I thought this was exactly the case where some of us Phobos
contributors got lambasted by Andrei and Walter for abusing @trusted.
The thing is, this is too easy to abuse, and too prone to careless
mistakes with nasty consequences. Suppose you have a template function:
auto func(T)(T t)
{
auto p = () @trusted { return &t; } ();
...
p.bar();
...
}
The problem is, the separation between p and p.bar() can be very large
in a complicated function, and during maintenance, somebody accidentally
introduces unsafe operations on p in the function body without realizing
that it came from a function marked @trusted. However, the compiler
won't catch this, because of the @trusted annotation.
Any exception to the strict usage of @trusted to me smells like a time
bomb waiting to explode. It may not be today or tomorrow, but sooner or
later somebody is going to slip up and the compiler won't help you. It's
bad enough that every single change to a @trusted function must be
vetted to ensure actual safety; now we have to also vet any modification
to any function that contains @trusted anonymous functions? In a large
template function, it's too easy to miss these @trusted sub-functions,
because if the code change is far away enough, the @trusted annotation
won't even show up in the diff. So reviewers may not even realize it's a
change that may have broken @trusted.
I'm pretty sure somebody brought up a case where such a hack was
actually necessary... but I'd still tread very, very carefully before
recommending such a thing to the general D coder.
T
--
The best compiler is between your ears. -- Michael Abrash
More information about the Digitalmars-d-announce
mailing list