在lambda捕获列表中通过常量引用传递 [英] Passing by constant reference in the lambda capture list

查看:179
本文介绍了在lambda捕获列表中通过常量引用传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个lambda函数,该函数需要在上下文中访问相当数量的变量。

I'm building a lambda function that requires access to a fair number of variables in the context.

const double defaultAmount = [&]{
    /*ToDo*/
}();

我宁愿不使用 [=] ,因为我不想制作很多有价证券。

I'd rather not use [=] in the list as I don't want lots of value copies to be made.

如果使用,我担心程序的稳定性[ &] ,因为我不想让lambda修改捕获集。

I'm concerned about program stability if I use [&] since I don't want the lambda to modify the capture set.

我可以通过const引用传递吗? [const&] 不起作用。

Can I pass by const reference? [const &] doesn't work.

也许一个好的编译器可以优化值副本,所以<$最好使用c $ c> [=]

Perhaps a good compiler optimises out value copies, so [=] is preferable.

推荐答案

您可以显式创建和捕获const引用。 :

You can create and capture const references explicitly:

int x = 42;
const int& rx = x;
auto l = [&rx]() {
    x = 5; // error: 'x' is not captured
    rx = 5; // error: assignment of read-only reference 'rx'
};

这篇关于在lambda捕获列表中通过常量引用传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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