[Issue 14162] New: Erratic inference of @safe for lambdas

via Digitalmars-d-bugs digitalmars-d-bugs at puremagic.com
Mon Feb 9 23:17:38 PST 2015


https://issues.dlang.org/show_bug.cgi?id=14162

          Issue ID: 14162
           Summary: Erratic inference of @safe for lambdas
           Product: D
           Version: D2
          Hardware: All
                OS: All
            Status: NEW
          Severity: normal
          Priority: P1
         Component: DMD
          Assignee: nobody at puremagic.com
          Reporter: bugzilla at digitalmars.com

Consider the code:
---------
@trusted auto trusted(alias fun)() { return fun(); }

@safe void func()
{
    char[3] s = "abc";
    string t = trusted!(() => cast(string)(s[]));
//test.d(6): Error: cast from char[] to string not allowed in safe code
    assert(t == "abc");
}

@safe void test() { func(); }
----------
The error is correct because the lambda is evaluated in the context of @safe
func(), not in the context of @trusted trusted(). But turn func() into a
template function:
---------
@trusted auto trusted(alias fun)() { return fun(); }

@safe void func()() // only change is add () to make it a template
{
    char[3] s = "abc";
    string t = trusted!(() => cast(string)(s[]));
    assert(t == "abc");
}

@safe void test() { func(); }
----------
And it now incorrectly compiles without error.

--


More information about the Digitalmars-d-bugs mailing list