@trusting generic functions
ag0aep6g via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sat May 28 07:40:50 PDT 2016
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.
More information about the Digitalmars-d-learn
mailing list