当C ++ lambda表达式通过引用有大量捕获时,未命名的函数对象的大小变大 [英] When a C++ lambda expression has a lot of captures by reference, the size of the unnamed function object becomes large
问题描述
以下代码:
int main(){
int a,b,c,d,e ,f,g;
auto func = [&](){cout< a<< b<< c<< d<< e - < f<< g < endl;};
cout<< sizeof(func)< endl;
return 0;
}
输出56使用 g ++ 4.8.2 / p>
由于所有局部变量都存储在同一个堆栈帧中,记住一个指针足以定位所有局部变量的地址。为什么lambda表达式构造了一个如此大的未命名函数对象?
我不明白你为什么感到惊讶。
C ++标准提供了一系列要求,每个实现都可以自由选择符合要求的策略。
为什么一个实现会优化lambda对象的大小?
具体来说,你是否意识到如何将生成的lambda代码绑定到生成的代码周围功能?
很容易说嘿!这可以优化!,但实际优化并确保它适用于所有边缘情况更难。所以,个人而言,我更喜欢一个简单和有效的实施,而不是一个拙劣的尝试优化它...
...特别是当工作周期<强> so easy ::
$ struct S {int a,b,c,d,e,f,g; };
int main(){
S s = {};
auto func = [&](){
std :: cout< s.a < s.b < s.c<< s.d < s.e << s.f < s.g<< \\\
;
};
std :: cout<< sizeof(func)< \\\
;
return 0;
}
The following code:
int main() {
int a, b, c, d, e, f, g;
auto func = [&](){cout << a << b << c << d << e << f << g << endl;};
cout << sizeof(func) << endl;
return 0;
}
outputs 56 compiled with g++ 4.8.2
Since all local variables are stored in the same stack frame, remembering one pointer is sufficient to locate the addresses of all local variables. Why the lambda expression constructs a so big unnamed function object?
I do not understand why you seem surprised.
The C++ Standard gives a set of requirements, and every single implementation is free to pick any strategy that meets the requirements.
Why would an implementation optimize the size of the lambda object ?
Specifically, do you realize how that would tie down the generated code of this lambda to the generated code for the surrounding function ?
It's easy to say Hey! This could be optimized!, but it's much more difficult to actually optimize and make sure it works in all edge cases. So, personally, I much prefer having a simple and working implementation than a botched attempt at optimizing it...
... especially when the work-around is so easy:
struct S { int a, b, c, d, e, f, g; };
int main() {
S s = {};
auto func = [&](){
std::cout << s.a << s.b << s.c << s.d << s.e << s.f << s.g << "\n";
};
std::cout << sizeof(func) << "\n";
return 0;
}
这篇关于当C ++ lambda表达式通过引用有大量捕获时,未命名的函数对象的大小变大的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!