Function's local variables allocated on the heap.

realhet real_het at hotmail.com
Sun Aug 31 21:36:16 UTC 2025


Hi,

I noticed that the local area of the myUi() function was 
allocated on the heap, not on the stack as it would be the usual 
case with functions.
Please explain me how the D compiler detects that. Does it knows 
that the myUi() function returns something, that contains a 
delegate which is referencing to a variable on the function's 
local area?
What is the trigger of this heap allocated function storage area?


```d
import std;

class Button
{
     string title;
     void delegate() onPress;

     this(string title, void delegate() onPress)
     {
         this.title = title, this.onPress = onPress;
     }

     void draw(){ writeln("Drawing ["~title~"]"); }
     void press(){ writeln("Pressing ["~title~"]"); onPress(); }
}

auto myUi()
{
     auto titles = ["Hello", "Hi", "Greetings"].cycle;
     Button btn;
     btn = new Button(titles.front, (){
         titles.popFront; btn.title = titles.front;
         writeln("Title changed");
     });
     return btn;
}

void main()
{
     auto ui = myUi;
     auto ui2 = myUi;

     foreach(i; 0..10){
         writeln("1---------");
         ui.draw;if(i%3) ui.press;
         writeln("2---------");
         ui2.draw;if(i%2) ui2.press;
     }
}
```


More information about the Digitalmars-d-learn mailing list