[Issue 17456] [REG2.075a] spurious lifetime diagnostic on delegates

via Digitalmars-d-bugs digitalmars-d-bugs at puremagic.com
Tue May 30 11:44:43 PDT 2017


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

ag0aep6g at gmail.com changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
             Status|NEW                         |RESOLVED
                 CC|                            |ag0aep6g at gmail.com
         Resolution|---                         |INVALID

--- Comment #2 from ag0aep6g at gmail.com ---
(In reply to b2.temp from comment #0)
> struct Foo
> {
>     private void delegate() dg;
>     void assign() @safe {dg = &sameThis;}
>     void sameThis(){}
> }
> ===
> 
> yield: "address of variable this assigned to this with longer lifetime"

As far as I see, the code is unsafe. Call `assign` on a Foo, then copy the Foo.
The context pointer of the new dg will refer to the old Foo. Let the old Foo go
out of scope. The context pointer now points to garbage.

I'm closing as invalid. Just reopen if I'm missing something.

In code:

----
struct Foo
{
    int x;
    private void delegate() dg;
    void assign() /*@safe*/ {dg = &sameThis;}
    void sameThis() { import std.stdio; writeln(x); }
}

void f(ref Foo dst)
    /* ref parameter instead of return value, because dmd is smart
    enough to avoid the copy when returning. */
{
    Foo foo;
    foo.x = 42;
    foo.assign();
    dst = foo;
}

void main()
{
    Foo foo;
    f(foo);
    (){ int[100] stomp = 13; }();
    foo.dg(); /* prints garbage (here: contents of 'stomp') */
}
----

--


More information about the Digitalmars-d-bugs mailing list