C++ lambda copy value in capture-list - c++

I have a program as below:
int main()
{
int val = 4;
auto add = [val](int a)->int{
val += 2;
return a+val;
};
cout << add(3) << endl;
cout << val << endl;
return 0;
}
There's a compiling error in Xcode: Cannot assign to a variable captured by copy in a non-mutable lambda.
My question is: if we choose to use the copy (using "=" or value name), can't this value be assigned a new value or changed?

Inside a lambda, captured variables are immutable by default. That doesn't depend on the captured variables or the way they were captured in any way. Rather, the function call operator of the closure type is declared const:
This function call operator or operator template is declared const
(9.3.1) if and only if the lambda-expression’s
parameter-declaration-clause is not followed by mutable.
Therefore, if you want to make the captured variables modifiable inside the body, just change the lambda to
auto add = [val] (int a) mutable -> int {
val += 2;
return a+val;
};
so the const-specifier is removed.

The operator () of a lambda is implicitly const unless the lambda is declared mutable - and you can't modify the data members in a const member function. This happens regardless of the type of the capture.

Just capture it by reference, it will work !!
auto add = [&val](int a) -> int{
//
}

Related

error: no matching member function for call to 'push_back' only instde std::for_each [duplicate]

I have a program as below:
int main()
{
int val = 4;
auto add = [val](int a)->int{
val += 2;
return a+val;
};
cout << add(3) << endl;
cout << val << endl;
return 0;
}
There's a compiling error in Xcode: Cannot assign to a variable captured by copy in a non-mutable lambda.
My question is: if we choose to use the copy (using "=" or value name), can't this value be assigned a new value or changed?
Inside a lambda, captured variables are immutable by default. That doesn't depend on the captured variables or the way they were captured in any way. Rather, the function call operator of the closure type is declared const:
This function call operator or operator template is declared const
(9.3.1) if and only if the lambda-expression’s
parameter-declaration-clause is not followed by mutable.
Therefore, if you want to make the captured variables modifiable inside the body, just change the lambda to
auto add = [val] (int a) mutable -> int {
val += 2;
return a+val;
};
so the const-specifier is removed.
The operator () of a lambda is implicitly const unless the lambda is declared mutable - and you can't modify the data members in a const member function. This happens regardless of the type of the capture.
Just capture it by reference, it will work !!
auto add = [&val](int a) -> int{
//
}

Why can we avoid specifying the type in a lambda capture? [duplicate]

This question already has answers here:
Implicit type in lambda capture
(2 answers)
Closed last year.
Why is the variable 'n' in 2nd usage of std::generate and within lambda capture not preceded with it's data type in below code?
I thought it's important to specify the datatype of all identifiers we use in a c++ code.
#include <algorithm>
#include <iostream>
#include <vector>
int f()
{
static int i;
return ++i;
}
int main()
{
std::vector<int> v(5);
auto print = [&] {
for (std::cout << "v: "; auto iv: v)
std::cout << iv << " ";
std::cout << "\n";
};
std::generate(v.begin(), v.end(), f);
print();
// Initialize with default values 0,1,2,3,4 from a lambda function
// Equivalent to std::iota(v.begin(), v.end(), 0);
std::generate(v.begin(), v.end(), [n = 0] () mutable { return n++; });
print();
}
Why is the variable 'n' in 2nd usage of std::generate and within lambda capture not preceded with it's data type in below code?
It's not preceded with a data type, because the grammar of C++ says that it doesn't need to - nor even allowed to - be preceded by a type name.
A type name isn't needed because the type is deduced from the type of the initialiser expression.
From cppreference:
A capture with an initializer acts as if it declares and explicitly captures a variable declared with type auto, whose declarative region is the body of the lambda expression (that is, it is not in scope within its initializer), [...]
Lambdas used the opportunity of a syntax that was anyhow fresh and new to get some things right and allow a nice and terse syntax. For example lambdas operator() is const and you need to opt-out via mutable instead of the default non-const of member functions.
No auto in this place does not create any issues or ambiguities. The example from cppreference:
int x = 4;
auto y = [&r = x, x = x + 1]()->int
{
r += 2;
return x * x;
}(); // updates ::x to 6 and initializes y to 25.
From the lambda syntax it is clear that &r is a by reference capture initialized by x and x is a by value capture initialized by x + 1. The types can be deduced from the initializers. There would be no gain in requiring to add auto.
In my experience n could have been just declared inside the lambda body with auto or int as datatype. Isnt it?
Yes, but then it would need to be static. This produces the same output in your example:
std::generate(v.begin(), v.end(), [] () mutable {
static int n = 0;
return n++; });
However, the capture can be considered cleaner than the function local static.

lambda capture by value mutable doesn't work with const &?

Consider the following:
void test( const int &value )
{
auto testConstRefMutableCopy = [value] () mutable {
value = 2; // compile error: Cannot assign to a variable captured by copy in a non-mutable lambda
};
int valueCopy = value;
auto testCopyMutableCopy = [valueCopy] () mutable {
valueCopy = 2; // compiles OK
};
}
Why is the first version a compile error when I've declared the lambda as mutable and captured value by value (which I thought made a copy of it)?
Tested with clang (x86_64-apple-darwin14.3.0), which is where the error message comes from, and Visual C++ (vc120).
[C++11: 5.1.2/14]: An entity is captured by copy if it is implicitly captured and the capture-default is = or if it is explicitly captured with a capture that does not include an &. For each entity captured by copy, an unnamed non-static data member is declared in the closure type. The declaration order of these members is unspecified. The type of such a data member is the type of the corresponding captured entity if the entity is not a reference to an object, or the referenced type otherwise. [..]
The type of value inside your lambda is const int, because it was captured by copy from a const int&.
Thus, even though the lambda's call operator function is not const (you marked the lambda mutable), the actual implicit member value is of type const int and cannot be mutated.
Frankly, this seems absurd; I would expect this rule to say that the referenced type loses constness, as it's a copy. The presence or absence of the mutable keyword on the lambda itself (and, thus, the presence or absence of the const keyword on the generated call operator function) should be the only access control here.
In C++14 you can work around this by capturing as [value=value], which uses the same rules as auto and thus drops the const. C++'s great, ain't it?
mutable allows a lambda to modify copy of a non-const parameter captured by copy, but it does not allow it for const parameters.
So this code works (and outputs inside 2 outside 1):
int a = 1;
[a]() mutable {
a = 2; // compiles OK
cout << "inside " << a << "\n";
}();
cout << " outside " << a << "\n";
But if we omit mutable, or make a const int, the compiler gives an error.
In our case, the first lambda gives an error because value is const:
void test( const int &value )
If we make copyValue const:
const int valueCopy = value;
then the same error will occur with the second lambda.

Passing by constant reference in the lambda capture list

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'
};
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(...);
Sadly the C++11 grammar does not allow for this, so no.
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();
}();

Where are lambda captured variables stored?

How is it possible that this example works? It prints 6:
#include <iostream>
#include <functional>
using namespace std;
void scopeIt(std::function<int()> &fun) {
int val = 6;
fun = [=](){return val;}; //<-- this
}
int main() {
std::function<int()> fun;
scopeIt(fun);
cout << fun();
return 0;
}
Where is the value 6 stored after scopeIt is done being called? If I replace the [=] with a [&], it prints 0 instead of 6.
It is stored within the closure, which - in your code - is then stored within std::function<int()> &fun.
A lambda generates what's equivalent to an instance of a compiler generated class.
This code:
[=](){return val;}
Generates what's effectively equivalent to this... this would be the "closure":
struct UNNAMED_TYPE
{
UNNAMED_TYPE(int val) : val(val) {}
const int val;
// Above, your [=] "equals/copy" syntax means "find what variables
// are needed by the lambda and copy them into this object"
int operator() () const { return val; }
// Above, here is the code you provided
} (val);
// ^^^ note that this DECLARED type is being INSTANTIATED (constructed) too!!
Lambdas in C++ are really just "anonymous" struct functors. So when you write this:
int val = 6;
fun = [=](){return val;};
What the compiler is translating that into is this:
int val = 6;
struct __anonymous_struct_line_8 {
int val;
__anonymous_struct_line_8(int v) : val(v) {}
int operator() () const {
return val; // returns this->val
}
};
fun = __anonymous_struct_line_8(val);
Then, std::function stores that functor via type erasure.
When you use [&] instead of [=], it changes the struct to:
struct __anonymous_struct_line_8 {
int& val; // Notice this is a reference now!
...
So now the object stores a reference to the function's val object, which becomes a dangling (invalid) reference after the function exits (and you get undefined behavior).
The so-called closure type (which is the class type of the lambda expression) has members for each captured entity. Those members are objects for capture by value, and references for capture by reference. They are initialized with the captured entities and live independently within the closure object (the particular object of closure type that this lambda designates).
The unnamed member that corresponds to the value capture of val is initialized with val and accessed from the inside of the closure types operator(), which is fine. The closure object may easily have been copied or moved multiple times until that happens, and that's fine too - closure types have implicitly defined move and copy constructors just as normal classes do.
However, when capturing by reference, the lvalue-to-rvalue conversion that is implicitly performed when calling fun in main induces undefined behavior as the object which the reference member referred to has already been destroyed - i.e. we are using a dangling reference.
The value of a lambda expression is an object of class type, and
For each entity
captured by copy, an unnamed non-static data member is declared in the closure type.
([expr.prim.lambda]/14 in C++11)
That is, the object created by the lambda
[=](){return val;}
actually contains a non-static member of int type, whose value is 6, and this object is copied into the std::function object.