What exactly does "@safe" mean?

Jonathan M Davis jmdavisProg at gmx.com
Sun Jun 2 01:50:02 PDT 2013


On Sunday, June 02, 2013 09:59:08 monarch_dodra wrote:
> On Saturday, 1 June 2013 at 22:15:00 UTC, Jonathan M Davis wrote:
> > On Saturday, June 01, 2013 23:41:32 monarch_dodra wrote:
> >> Now, it was *my* fault for calling emplace with an already
> >> built
> >> object, but it was the (@trusted) emplace that clobbered-it.
> > 
> > Well, given that the safety of the operation relies on what's
> > being passed in,
> > the operation itself can't reasonably be marked as @safe,
> > because you can't
> > guarantee that the operation isn't going to corrupt memory.
> 
> But isn't that exactly the same as my "void foo(int* p) @safe{*p
> = 0}" example ? That relies on what is being passed in to
> guarantee safety :/
> 
> @confused

I don't know. The function isn't doing anything unsafe in and of itself. foo 
_can_ be marked as @safe, because none of the operations that it's doing are 
unsafe. The problem is when the caller does something unsafe. So, maybe that's 
the answer. It's the caller which can't be marked as @safe, because it's doing 
something stupid. foo isn't doing anything unsafe, so it _can_ be @safe.

I think that part of the problem is the fact that @safety is generally viewed 
with the idea that unsafe stuff is called by safe stuff and not that unsafe stuff 
is called by safe stuff. And these cases under discussion are cases where the 
safe stuff ends up corrupting stuff if called from unsafe stuff.

So, maybe emplace should be marked as @trusted (assuming that it can't corrupt 
anything if called from an @safe function and that its safety does not depend 
on its arguments). It _is_ a bit of a tough topic though.

- Jonathan M Davis


More information about the Digitalmars-d mailing list