C ++ Lambda生命周期 [英] C++ lambda lifecycle

查看:114
本文介绍了C ++ Lambda生命周期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,运行时会发生什么?

In the following code, what happens at runtime?

while ( ([]()->bool { return something(); })() ) {
    ...
}

  1. lambda实例仅创建一次,并在后续迭代中重复使用.
  2. 每次迭代都会创建一个新实例,该实例只能使用一次.
  3. 以上都不是(请解释).

最初,在我看来,它是在每次迭代中都重新创建的,但我想知道编译器是否进行了某种优化.

Initially it seems obvious to me that it's re-created in every iteration, but I wonder if the compiler does some kind of optimization.

推荐答案

首先要强调一些标准引号,

First a couple of standard quotes, with my emphasis:

[stmt.while]/1

在while语句中,重复执行子语句,直到 条件的值([stmt.select])变为false. 测试 发生在子语句的每次执行之前.

In the while statement the substatement is executed repeatedly until the value of the condition ([stmt.select]) becomes false. The test takes place before each execution of the substatement.

[expr.prim.lambda]/2

lambda表达式是一个prvalue,其结果对象称为 关闭对象.

A lambda-expression is a prvalue whose result object is called the closure object.

上面的用法告诉我们([]()->bool { return something(); })()是在每次迭代之前求值的.并且子表达式[]()->bool { return something(); }创建一个prvalue.因此,只有在评估完整表达式时,它才能栩栩如生.

The above tells use that ([]()->bool { return something(); })() is evaluated before every iteration. And that the sub-expression []()->bool { return something(); } creates a prvalue. So it springs to life only during the evaluation of the full expression.

因此,法律的枯燥无味的文字表明,每次评估条件时,构造和破坏的对象都是封闭类型的另一个对象.

So the dry letter of the law would indicate it's a different object of the closure type that is constructed and destructed every time the condition is evaluated.

但是编译器并不愚蠢.我认为,按照常规规则,很有可能会将其优化为直接调用something()的方式.那是因为lambda的构造和破坏没有明显的副作用.

But compilers are not stupid. I believe that under the as-if rule it's more than likely to be optimized into a direct call to something(). That is because the construction and destruction of the lambda does not have observable side effects.

如果我们确实使用了 godbolt在线编译器查看器之类的工具,我们会看到GCC 7.2在-O1处将直接调用该函数. Clang 5.0也是如此,但是我不得不将优化推向-O2才能实现.

And if we indeed use a tool like the godbolt online compiler viewer, we see that GCC 7.2 at -O1 will call the function directly. And so does Clang 5.0, but I had to crank optimizations to -O2 for that to happen.

这篇关于C ++ Lambda生命周期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆