Gotchas for returning values from blocks

jmh530 via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Jun 13 07:16:58 PDT 2016


On Monday, 13 June 2016 at 01:41:07 UTC, Mike Parker wrote:
>
> 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.

So returning a reference to something on the stack is a bad idea, 
but copying the value would be fine.


More information about the Digitalmars-d-learn mailing list