On Sunday, 12 June 2016 at 18:24:58 UTC, jmh530 wrote:

garbage collected variable and assign it to it. Everything seems to work fine. I'm just not sure if there are any gotchas to be aware of.

class Foo
{
        int baz = 2;
}

void main()
{
        import std.stdio : writeln;
        
        Foo foo;
        {
                Foo bar = new Foo();
                foo = bar;
        }
        //bar is now out of scope
        assert(foo.baz == 2);
}

Everything works fine in your example because 'new' always allocates on the heap. Anything allocated on the stack is not guaranteed to be valid after the scope exits:

struct Foo
{
    int baz;
    ~this() { baz = 1; }
}

void main()
{
    import std.stdio : writeln;

    Foo* foo;
    {
        Foo bar = Foo(10);
        foo = &bar;
    }
    //bar is now out of scope
    assert(foo.baz == 10);
}

Struct constructors are always run when exiting a scope. More importantly, the pointer to bar is only valid until the stack address where it lives is overwritten by another stack allocation. In this example, there's no chance for that to happen before I access it, but it could happen at any time.

Reply via email to