On 05/28/2016 02:43 PM, Lodovico Giaretta wrote:
struct S1
{
     int doSomething() @safe
     {
         // do something safely
         return 1;
     }
}

struct S2
{
     int doSomething() @system
     {
         // do something usafe
         return 2;
     }
}

auto doSomethingDumb(T)(ref T t)
{
     T* pt = &t;
     return pt.doSomething();
}

auto s1 = S1();
auto s2 = S2();
auto x = doSomethingDumb(s1); // this call should be possible in @safe code
auto y = doSomethingDumb(s2); // this should only be possible in @system
code

I'm not sure if should mention it, but there is this little trick:

----
auto doSomethingDumb(T)(ref T t)
{
    T* pt;
() @trusted { pt = &t; } (); /* Ok, because the reference is never returned. NOTE: DON'T RETURN THIS POINTER! */
    return pt.doSomething();
}
----

Though in cases like this it's kind of an anti-pattern. The trusted code itself isn't actually safe, but the compiler thinks so. So you have to manually verify that doSomethingDumb is safe, even though it's not marked @trusted. That's pretty bug-prone.

Reply via email to