在c 11 lambdas
{std :: cout 此代码使用[&]语法通过引用捕获变量x。问题出现了该程序是否保证在不调用未定义的行为的情况下输出5。答案:是
,代码可确保正常工作。在检查基础标准措辞之前,必须注意,该代码的功能按C委员会的意图运行。但是,在此问题上尚不清楚C 11标准的最初措辞,导致2011年CWG发行以提供澄清。 This issue is being addressed in the ongoing development of the C standard.#include
#include
std::function make_function(int& x) {
return [&]{ std::cout According to [expr.prim.lambda]/17 of the C standard, only id-expressions referring to entities captured by copy are transformed into a member access on the lambda closure type.指代通过参考捕获的实体的ID表达是单独的,并继续表示它们在封闭范围中表示的相同实体。
在上面的代码中,被捕获的实体是make_function函数的参数x,它属于lambda的到达范围内。因此,lambda表达式中的参考x是指主函数中声明的原始变量。最初可能会出现问题,因为在make_function函数返回后,在其寿命之外被引用x。但是,在有限的情况下,可以在其寿命之外引用参考文献。通常,引用要么在范围内声明,要么是类成员,在这种情况下,类本身必须在其寿命内。因此,标准不会明确禁止在其寿命外使用参考文献。 This loophole allowed for the capturing of references by reference in lambda expressions to be supported.
CWG Issue 2012 and Future Clarification
CWG issue 2012 was raised to address the oversight that references could be referenced outside their lifetime under certain circumstances.该问题的解决方法无意间通过参考引用来影响lambda捕获的规范。但是,预计该回归将在发布C 17之前修复。
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3