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.
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'
};