Determining @trusted-status

ag0aep6g anonymous at example.com
Fri May 29 06:39:18 UTC 2020


On 29.05.20 08:28, JN wrote:
> Alternatively you could just use @trusted blocks. Unsafe blocks are a 
> common practice in languages like C# or Rust when it comes to calling 
> unsafe code. @safe isn't about 100% bulletproof safety. @safe is (should 
> be) about not having memory related errors outside of @trusted code, 
> minimizing the surface area for errors.

Note that an "@trusted block" is really a nested @trusted function being 
called immediately. Being an @trusted function, the "block" must have a 
safe interface. I.e., its safety cannot depend on its inputs. The inputs 
of a nested function include the variables of the surrounding function. 
@trusted blocks often violate the letter of @trusted law, because people 
forget/ignore that.

For example, the second @trusted block here is strictly speaking not 
allowed, because its safety depends on `p`:

     void main() @safe
     {
         import core.stdc.stdlib: free, malloc;
         int* p = () @trusted {
             return cast(int*) malloc(int.sizeof);
         } ();
         if (p is null) return;
         /* ... else: do something with p ... */
         () @trusted { free(p); } ();
     }


More information about the Digitalmars-d-learn mailing list