为什么在C ++ 11中按值传递的lambda参数是只读的? [英] Why are lambda arguments passed by value read-only in C++11?
问题描述
当函数按值接受参数时,通常可以对其进行修改。但是,lambda似乎并非如此。为什么?
When a function takes an argument by value, it can usually modify it. However, this does not seem to be the case with lambdas. Why?
int main()
{
int x = 0;
auto lambda = [x] { x = 1; }; // error: assignment of read-only variable ‘x’
return 0;
}
推荐答案
Herb Sutter回答了这个问题< a href = http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3424.pdf rel = noreferrer>此处如下;
Herb Sutter answered the question here as follow;
以这个稻草人为例,程序员通过值捕获本地
变量并尝试修改捕获的值(即
lambda对象的成员变量):
Consider this straw man example, where the programmer captures a local variable by value and tries to modify the captured value (which is a member variable of the lambda object):
int val = 0;
auto x = [=](item e) // look ma, [=] means explicit copy
{ use(e,++val); }; // error: count is const, need ‘mutable’
auto y = [val](item e) // darnit, I really can’t get more explicit
{ use(e,++val); }; // same error: count is const, need ‘mutable’
该功能似乎是出于担心用户
可能不会意识到自己已获得副本的考虑而添加的,尤其是由于Lambda
是可复制的,因此他可能正在更改其他Lambda的副本。
This feature appears to have been added out of a concern that the user might not realize he got a copy, and in particular that since lambdas are copyable he might be changing a different lambda’s copy.
注意:这是更改功能的建议书。
Note: That is a proposal paper to change the feature.
这篇关于为什么在C ++ 11中按值传递的lambda参数是只读的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!