Passing by constant reference in the lambda captur

2019-06-14 23:59发布

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.

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

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

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

标签: c++ c++11 lambda
4条回答
别忘想泡老子
2楼-- · 2019-06-15 00:13

Sadly the C++11 grammar does not allow for this, so no.

查看更多
疯言疯语
3楼-- · 2019-06-15 00:26

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'
};
查看更多
Bombasti
4楼-- · 2019-06-15 00:27

The capture list is limited in what can be captured; basically by-value or by-reference (named or by default), the this pointer and nothing.

From the cppreference;

capture-list - a comma-separated list of zero or more captures, optionally beginning with a capture-default. Capture list can be passed as follows (see below for the detailed description):

  • [a,&b] where a is captured by value and b is captured by reference.
  • [this] captures the this pointer by value
  • [&] captures all automatic variables odr-used in the body of the lambda by reference
  • [=] captures all automatic variables odr-used in the body of the lambda by value
  • [] captures nothing

You could create local const& to all the object you wish to capture and use those in the lambda.

#include <iostream>

using namespace std;

int main()
{
    int a = 5;
    const int& refa = a;
    const int b = [&]() -> int {
        //refa = 10; // attempts to modify this fail
        return refa;
    }();
    cout << a << " " << b << endl;
}

The capture could be either for all the references, or an explicit list what is required;

const int b = [&refa]()

Another alternative is not to capture the local variables at all. You then create a lambda that accepts as arguments the variables you need. It may be more effort as the local variable count grows, but you have more control over how the lambda accepts its arguments and is able to use the data.

auto lambda = [](const int& refa /*, ...*/) { */...*/ }
lambda(...);
查看更多
Melony?
5楼-- · 2019-06-15 00:32

You can capture a constant reference to an object, not an object itself:

A a;
const A& ref_a = a;

const double defaultAmount = [&]{
    ref_a.smth();
}();
查看更多
登录 后发表回答