While we're on the subject of escape analysis...

Hxal hxal at freenode.irc
Thu Oct 30 21:14:25 PDT 2008


Hxal Wrote:
> Note that this only works for a single level of nesting.
> (Can't return the object up the stack through more steps, that'd require
> every scope to allocate its own secondary stack, which requires a heap
> allocation and defeats the purpose.)

Sorry for the multiple posts, that's what I get for posting at 4am.
The above is not true. Since all that ever ends up on the secondary stack
are return values, a function can simply pass the ownership to its
caller, by not cleaning it up its part of the secondary stack.

There's also one gotcha, the programmer needs to take care not to
leak memory. The leak disappers when the outer scope is left, and the
compiler can take steps to reduce it, but there's always the possibility
to create it.

Example:

scope Foo[] bar ()
{
    scope(caller) Foo foo1 = new Foo;
    scope(caller) Foo foo2 = new Foo;
    if (blah) foo1 = null;
    return [foo1, foo2];
}

In this case foo1 eats up secondary stack space, even when it's
not actually used. Its memory cannot be reclaimed until bar's caller
returns. But once that happens everything is OK again.

Please don't attack the syntax, since it's only illustratory.




More information about the Digitalmars-d mailing list