Gotchas for returning values from blocks

Mike Parker via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Jun 12 18:41:07 PDT 2016


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.


More information about the Digitalmars-d-learn mailing list