Lambda捕获:使用还是不使用初始化程序? [英] Lambda capture: to use the initializer or not to use it?

查看:80
本文介绍了Lambda捕获:使用还是不使用初始化程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下最小示例:

int main() {
    int x = 10;    
    auto f1 = [x](){ };
    auto f2 = [x = x](){};
}

我不止一次看到这样的初始化器 [x = x] ,但我不能完全理解它,为什么我应该使用它代替 [x] 。 br>
我可以得到 [& x = x] [x = x + 1]之类的含义(如文档所示,以及为什么它们与 [x] 当然,但是仍然无法弄清示例中的lambda之间的差异。

I've seen more than once such an use of the initializer [x = x], but I can't fully understand it and why I should use it instead of [x].
I can get the meaning of something like [&x = x] or [x = x + 1] (as shown in the documentation and why they differ from [x], of course, but still I can't figure out the differences between the lambdas in the example.

它们是完全可互换的还是我看不到有什么区别?

Are they fully interchangeable or is there any difference I can't see?

推荐答案

有各种各样的极端情况,几乎都是沸腾的降至 [x = x] 衰减; [x] 不会衰减。

There are various corner cases that pretty much boils down to "[x = x] decays; [x] doesn't".


  • 捕获对函数的引用:

  • capturing a reference to function:

void (&f)() = /* ...*/;
[f]{};     // the lambda stores a reference to function.
[f = f]{}; // the lambda stores a function pointer


  • 捕获数组:

  • capturing an array:

    int a[2]={};
    [a]{}     // the lambda stores an array of two ints, copied from 'a'
    [a = a]{} // the lambda stores an int*
    


  • 捕获具有简历资格的内容:

  • capturing a cv-qualified thing:

    const int i = 0; 
    [i]() mutable { i = 1; } // error; the data member is of type const int
    [i = i]() mutable { i = 1; } // OK; the data member's type is int
    


  • 这篇关于Lambda捕获:使用还是不使用初始化程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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