Lambda捕获的生命周期 [英] Lifetime of lambda captures
问题描述
给出以下程序:
#include <iostream>
#include <memory>
using namespace std;
int main() {
std::shared_ptr<int> i(new int(42));
cout << i.use_count() << endl;
auto fn = [=](){i; cout << 42 << endl;};
cout << i.use_count() << endl;
return 0;
}
编译器何时确定将捕获哪些对象?
lambda表达式中从未使用shared_ptr i
.因此,在正常功能中,我会假设优化器将删除此nop语句.
但是如果删除它,编译器可能会认为不需要捕获i
.
When does the compiler decide which objects it will capture?
The shared_ptr i
is never used in the lambda expression. So in a normal function I would assume that the optimizer will remove this nop statement.
But if it is removed the compiler could think that i
needs not to be captured.
因此,使用gcc时,该程序将始终产生1,2作为输出.
但这是标准所保证的吗?
So with gcc this program will always produce 1,2 as an output.
But is this guaranteed by the standard?
推荐答案
如果我们转到 lambda函数具有以下解释:
If we go to cppreference page on lambda function they have the following explanation:
[=]通过值捕获lambda正文中提到的所有自动变量
[=] captures all automatic variables mentioned in the body of the lambda by value
并进一步说:
捕获列表是用逗号分隔的零个或多个捕获列表,可以选择以捕获默认值"开头.唯一的捕获默认值是& (隐式地捕获使用过的自动变量,并通过引用来对此)和=(隐式捕获到被使用的自动变量,并通过值来).
使用过的的参考部分说:
如果变量的名称显示为可能评估的表达式,则该变量为odr-used,除非以下所有条件为 正确:
a variable is odr-used if its name appears as a potentially-evaluated expression, except if all of the following is true:
- 将左值到右值转换应用于表达式会产生一个常量表达式,该常量表达式不会调用非平凡的函数
- 表达式是舍弃值表达式或从左值到右值的转换
该异常不适用于i
,因此将捕获i
.
The exceptions do not apply to i
so i
will be captured.
同意草稿C ++ 11个标准部分5.1.2
Lambda表达式段落 11 其中说:
Which agrees with the draft C++11 standard section 5.1.2
Lambda expressions paragraph 11 which says:
如果lambda表达式具有关联的capture-default和它的 复合语句odr-使用(3.2)此变量或自动变量 存储期限,并且未明确捕获使用过odd的实体, 然后称该odd用过的实体被隐式捕获;这样的 实体应在lambda的适用范围内声明 表达.
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.
这篇关于Lambda捕获的生命周期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!