Where is the captured variables allocated in nested function in C#

微笑、不失礼 提交于 2020-01-23 16:40:49

问题


The nested function mentioned means it could be both lambda function and local function.

I am curious about where the captured variables are allocated.

For Example:

private Func<int> Test(int arg)
{
    var x = arg;
    return () => x;
}

The local variable x is captured by the lambda function returned.

Then where is this x allocated in memory? Is it on stack or heap memory?

If this x is on stack, any further call on Test could change the value of x and the behavior of the lambda function returned could be incorrectly modified.

But if it is dynamically allocated on heap memory, it would not be like a local variable any more.

Was it first allocated in stack and transferred to heap right on Test returns? (I guess not because it sounds like unnecessarily costing some resources, but how does it work to make it available to access this x after Test returns?)


回答1:


Stack vs heap isn't a very useful distinction here, but I can give you an idea of what happens. The compiler re-writes this code behind the scenes. It adds a class to the project which has an integer value as a member. Then both this function and the lambda function get a reference to the same instance of this new class.

At least, that's how this was handled the last time I read about it, which was admittedly some time ago now... but I doubt it's changed much. Welcome to programming, where everything you think you know is really a snapshot of how things were at some time in the past.



来源:https://stackoverflow.com/questions/50082471/where-is-the-captured-variables-allocated-in-nested-function-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!