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.
Sadly the C++11 grammar does not allow for this, so no.
You can create and capture const references explicitly:
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;
You could create local
const&
to all the object you wish to capture and use those in the lambda.The capture could be either for all the references, or an explicit list what is required;
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.
You can capture a constant reference to an object, not an object itself: