mercredi 2 août 2023

Where is a lambda stored?

This is follow-up question to Does a C++ lambda have a limited life?.

In my previous question, trying to use a lambda after it had gone out of scope caused a crash. While it shouldn't have been surprising, I think I was using an incorrect mental model of where the lambda was stored, which made me think that it would always exist, even if it was out of scope.

Perhaps it's because I often work with microcontrollers, where code executes from non-volatile FLASH memory, which is quite separate from data memory (e.g. the stack). But I imagined that creating a lambda was equivalent to explicitly writing a stand-alone function, but with a more convenient syntax. I.e:

void SaySomething()
{
    cout << "Hello" << endl;
}

int main()
{
    AcceptFunction([](){cout << "Hello" << endl;});    // I thought that this
    AcceptFunction(SaySomething);                    // was the same as this
}

What I imagined was that the lambda compiles to actual code which exists statically alongside other non-lambda code, and AcceptFunction is passed a pointer to that code. In which case, that code would always exist in memory, even if the lambda was out of scope.

But my program crashes, so this can't be true. So where is that code? Is it on the stack? And if so, would the behaviour be different on an architecture with FLASH memory where code cannot be run from the stack?

Update

Just to note that this question is about where the lambda is physically stored. I am not wishing the behaviour to be different, or for the lambda's destructors not to be called.

Aucun commentaire:

Enregistrer un commentaire