gpt4 book ai didi

c++ - 总是在 lambda 表达式中捕获所有内容是一种不好的做法吗?

转载 作者:IT老高 更新时间:2023-10-28 22:02:20 27 4
gpt4 key购买 nike

std::function<int()> void f1()
{
int a, b, c, d, ..., x, y, z;

return [=] { return a + b + c; };
}

对比

std::function<int()> void f2()
{
int a, b, c, d, ..., x, y, z;

return [a, b, c] { return a + b + c; };
}

不用说,前者比后者更短、更方便、更优雅。

不过,我还是担心:

从性能的角度来看,后者总是比前者更好吗?

标准是否保证 lambda 表达式仅捕获必要的变量?即在前一个例子中,只捕获了 a, b, c,未使用的变量 d, ..., x, y, z 没有。

最佳答案

该标准保证,如果您执行默认捕获,则该默认捕获将从周围环境中捕获的唯一变量是您在 lambda 中实际使用的变量。

因此,指定要捕获的单个变量可以作为您期望使用的文档,但绝不应该影响性能。

对于任何关心的人,标准中的确切措辞是 (§5.1.2/11, 12):

11 If a lambda-expression has an associated capture-default and its compound-statement odr-uses (3.2) this or a variable with automatic storage duration and the odr-used entity is not explicitly captured, then the odr-used entity is said to be implicitly captured; such entities shall be declared within the reaching scope of the lambda expression. [Note elided]

12 An entity is captured if it is captured explicitly or implicitly. [...]

总结

隐式捕获规范([=][&])只会捕获 lambda 中使用的变量,因此隐式与显式捕获永远不会影响性能。

关于c++ - 总是在 lambda 表达式中捕获所有内容是一种不好的做法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19018100/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com