Why is variable capturing in lambdas so complex? [closed]
I was wondering about the new C++11 lambda functionality, a wonderful addition in my humble opinion, but I really don't get开发者_StackOverflow the whole variable capturing part. In short my question comes down to "why did the committee decide for this and did not just use [&]
functionality (possibly with a keyword then)?"
At first I thought 'wow, C++
does it again and gives us even more powerful lambdas, sad of the syntax though'. However, then I tried to think of real, useful cases for this complex lambdas I couldn't think of any.
First, you obviously need it if you want to mix pass-by-reference and pass-by-value. So then the question is, do we actually need pass-by-value in the lambda construct. What is wrong with creating a temporary inside the lambda body. This is similar if you want a copy of an upper scope variable in the body of a loop, we also don't write [x] while(...) { ... }
. Am I missing something here that makes passing by value really necessary and you cannot fall back on constructing a copy yourself?
So we come to the second part, suppose pass-by-value is not necessary, with the current syntax you can specify which variables you want to capture and which not. Once again I do not see the benefit. The lambda is written in local scope, same as the variable. Why would you need to restrict access to these variables? It's not an interface, not another context and it shouldn't even be another programmer. It won't optimize it for compilers either, because using [&]
or mentioning each used variable yourself should come down to the same code.
Now, I do know I don't grasp C++ to its' fullest and the people on the committee know better than me. So, which of my arguments are wrong (or what did I miss) and why did they not just decide on using the [&]
functionality, preferably with a keyword instead of the current (quite ugly) syntax.
You need by-reference for efficiency.
You need by-value to allow the function object to leave the scope of the local variable which it captures.
std::function<void()> get_foo (const std::string & bar)
{
return [=] () {something with bar;}
}
...and the decision against a new keyword is mainly because of backward compatibility. If you introduce new keywords you might break existing code which uses that keyword as a regular identifier.
Even if you break only 0.01% of existing code, you do not want to create costs for such a change, if you can prevent it.
精彩评论