Encapsulating trust

monarch_dodra via Digitalmars-d digitalmars-d at puremagic.com
Mon Sep 1 10:48:58 PDT 2014


On Monday, 1 September 2014 at 16:36:04 UTC, Daniel Murphy wrote:
> I don't think this is a good idea.  Each time @trusted is used, 
> it should be on a function that is completely @safe to call.  I 
> think this is worth more than the cost in verbosity.
>
> Lambdas and nested functions are special in that they can't be 
> called from other code, so they only have to be @safe in the 
> context of the enclosing function.  They do still need to make 
> sure they don't violate @safe, otherwise the entire enclosing 
> function will need to be manually checked.
>
> eg
> void fun(int a) @safe
> {
> ...
>    p = @trusted () { return &a; }
> ...
> }
>
> This function is now essentially @trusted, because although the 
> unsafe '&' operation was inside the trusted block, the @safe 
> function now has a pointer it should not have been able to get.

I feels like you are missing the point of the @trusted lambda 
construct, in that is meant to be used in generic code, where you 
know a *piece* of a function is provably safe (eg: @trusted), but 
not all of it: The rest of the code depends on the inferred 
attributes of the parameter-dependent code.

If your function is not generic, then just mark it as @trusted, 
and then that's that.

Another alternative I had proposed was one of being able to 
simply create blocks with attributes. EG:

void foo(T)(T t)
{
     t.doSomething(); //May or may not be safe.

     nothrow
     {
         ... //Do "critical" code that can't throw here.
     }

     @trusted
     {
         ... //This slice of code is trusted.
     }

     @safe @nogc
     {
         ... //Have the compiler enforce only @safe and @ngc code 
goes here.
     }
     return t;
}


More information about the Digitalmars-d mailing list