Re: Why is the lambda capture-default [=] read-only?
Am 21.11.2012 21:55, schrieb DeMarcus:
When compiling the following with gcc 4.7.2 ...
#include <iostream>
#include <functional>
int main()
{
int myInt = 10;
std::function<void()> fnc =
[=]
{
myInt++; // Error here.
std::cout << myInt << std::endl;
};
fnc();
return 0;
}
... I get the following error.
error: increment of read-only variable ?myInt?
I don't understand why the myInt copy is read-only.
Because const functors are the mostly what people actually want to use,
therefore the lambda syntax (which is to great extends syntactic sugar)
was "optimized" for this use-case.
Is it connected to some programming paradigm like functional programming?
If so, is there a good website explaining the theory behind it?
There is no fundamental limitation for read-only lambda closures. Just
add "mutable" to the declarator. In your example this would mean to
rewrite your code as follows:
#include <iostream>
#include <functional>
int main()
{
int myInt = 10;
std::function<void()> fnc =
[=] () mutable
{
myInt++; // Error here.
std::cout << myInt << std::endl;
};
fnc();
return 0;
}
HTH & Greetings from Bremen,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]