gpt4 book ai didi

c++ - 为什么 lambda 的调用运算符隐式为 const?

转载 作者:IT老高 更新时间:2023-10-28 21:56:21 45 4
gpt4 key购买 nike

我在下面的函数中有一个小的“lambda 表达式”:

int main()
{
int x = 10;
auto lambda = [=] () { return x + 3; };
}

下面是为上述 lambda 表达式生成的“匿名闭包类”。

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

最佳答案

找到这个 paper由 Herb Sutter 在 open-std.org 讨论这个问题。

The odd couple: Capture by value’s injected const and quirky mutable
Consider this strawman 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’

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.

上面的引用和示例说明了为什么标准委员会可能默认将其设为 const 并要求 mutable 对其进行更改。

关于c++ - 为什么 lambda 的调用运算符隐式为 const?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53445857/

45 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com