On Tue, 09 Mar 2010 13:35:41 -0500, Ali Çehreli <acehr...@yahoo.com> wrote:

bearophile wrote:
m Wrote:
Can a function return a function as a return value?
as a delegate?
 Yes, you can do those things. In D2 you can return a clusure too:

Is closure a separate feature, or are delegates closures?

A closure is a separate feature.

Basically, a closure is a delegate with a stack frame that is allocated on the heap. The advantage is you can pass it around and not worry about the context becoming invalid.

In D1, for example, you could do what bearophile did, but it would result in memory corruption:

void delegate(int) adder(int x)
{
  void dg(int y)
  {
     return x + y;
  }
  return &dg;
}

The problem with this is that x is valid in the context of foo, not the context of the delegate. Therefore, when foo returns, it's stack-based frame can be overwritten, corrupting the value for x.

In D2, the above code makes the D compiler allocate foo's stack frame on the heap, so even when foo returns, its stack frame is valid for the delegate to refer to.

-Steve

Reply via email to