为什么lambda的call-operator隐式为const? [英] Why is a lambda's call-operator implicitly const?
问题描述
我在下面的函数中有一个小的"lambda表达式":
I have a small "lambda expression" in the below function:
int main()
{
int x = 10;
auto lambda = [=] () { return x + 3; };
}
下面是为上述lambda表达式生成的匿名闭包类".
Below is the "anonymous closure class" generated for the above lambda expression.
int main()
{
int x = 10;
class __lambda_3_19
{
public: inline /*constexpr */ int operator()() const
{
return x + 3;
}
private:
int x;
public: __lambda_3_19(int _x) : x{_x}
{}
};
__lambda_3_19 lambda = __lambda_3_19{x};
}
由编译器生成的闭包的"operator()"是隐式常量.为什么标准委员会默认将其设置为 const
?
The closure's "operator()" generated by the compiler is implicitly const. Why did the standard committee make it const
by default?
推荐答案
来自 cppreference
除非在lambda表达式中使用了关键字
mutable
,否则函数调用运算符是const限定的,并且通过复制捕获的对象在此operator中是不可修改的()
Unless the keyword
mutable
was used in the lambda-expression, the function-call operator is const-qualified and the objects that were captured by copy are non-modifiable from inside thisoperator()
对于您来说,复制捕获的内容是不可修改的.
In your case, there is nothing that, captured by copy, is modifiable.
我想,如果你写的东西是
I suppose that, if you write something as
int x = 10;
auto lambda = [=] () mutable { x += 3; return x; };
const
应该消失
-编辑-
OP精确
我已经知道添加可变变量可以解决此问题.问题是我想了解默认情况下使lambda不可变的原因.
I already knew that adding mutable will solve the issue. The question is that I want to understand the reason behind making the lambda immutable by default.
我不是语言律师,但我看来这很明显:如果您将 operator()
设为 const
,那么您将无法做到
I'm not a language lawyer but this seems me obvious: if you make operator()
not const
, you can't make something as
template <typename F>
void foo (F const & f)
{ f(); }
// ...
foo([]{ std::cout << "lambda!" << std::endl; });
我的意思是...如果 operator()
不是 const
,则不能使用将它们作为 const
引用传递的lambda.
I mean... if operator()
isn't const
, you can't use lambdas passing they as const
reference.
并且当不是严格需要时,应该是一个不能接受的限制.
And when isn't strictly needed, should be an unacceptable limitation.
这篇关于为什么lambda的call-operator隐式为const?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!