Thread overview
Function's local variables allocated on the heap.
6 days ago
realhet
6 days ago
Ali Çehreli
5 days ago
realhet
6 days ago

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?

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;
    }
}
6 days ago
On 8/31/25 2:36 PM, realhet wrote:
> 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.

Unless that's an optimization, that part would be the same: on the stack. However, because the delegate necessitates long-term lifetime, its context has to be on GC memory.

So, either the compiler allocates on the heap and uses that for local stack frame, or allocates on the stack and then copies to heap. I think the former is not complicated. I am guessing...

> 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?

Yes.

Ali

5 days ago
On Sunday, 31 August 2025 at 22:11:26 UTC, Ali Çehreli wrote:
> On 8/31/25 2:36 PM, realhet wrote:
> ...long-term lifetime...

Very cool feature.
Even a function body can be used to make a composition of multiple objects. It acts like a class constructor, but with cleaner, simpler syntax, and automatically deallocated by GC.