I have been reading Lambda capture as const reference?
It is an interesting feature, and sometimes I also wish this feature to exist, especially when I have huge data, which I need to access inside a lambda function.
My follow up questions -
- Should we capture by const reference in lambda? If yes, how should it be behave?
(Edit - I am also interested in the behaviour of the lifetime of the captured variable.) - Is there any possible downside, by introducing it in the C++ grammar? (I can't think of any)
Let us assume we can.
We assume [const &]
as syntax to capture.
int x = 10;
auto lambda = [const & x](){ std::cout << x << std::endl; };
lambda(); // prints 10, great, as expected
x = 11;
lambda(); // should it print 11 or 10 ?
My intuition is that is should behave just like [&]
but the captured value should not be allowed to modify.
template<typename Func>
void higher_order_function(int & x, Func f)
{
f(); // should print 11
x = 12;
f(); // should print 12
}
void foo()
{
int x = 10;
auto c = [const & x] () { std::cout << x << std::endl; };
c(); // should print 10
x = 11;
c(); // should print 11
higher_order_function(x, c);
auto d = [const & x] () { x = 13; }; // Compiler ERROR: Tried to assign to const qualified type 'const int &'!
}