c++ - 嵌套的 lambda 和可变关键字

标签 c++ c++11 gcc lambda clang

考虑以下代码:

void f() {
    int a = 3;
    [=]() {
        [=] () mutable {
            a = 5;
        }();
    }();
}

它在 Clang ( https://godbolt.org/z/IEXotM) 上编译,但不在 GCC (https://godbolt.org/z/xWXFe6) 上编译。 GCC 错误:

<source>: In lambda function:

<source>:5:15: error: assignment of read-only variable 'a'

    5 |             a = 5;

      |             ~~^~~

Compiler returned: 1

根据 https://en.cppreference.com/w/cpp/language/lambda ,

Optional sequence of specifiers.The following specifiers are allowed:

mutable: allows body to modify the parameters captured by copy, and to call their non-const member functions

Clang 在这里的行为似乎是正确的。是这样吗?

最佳答案

如果您从引用的链接底部开始阅读,您可以阅读:

If a nested lambda m2 captures something that is also captured by the immediately enclosing lambda m1, then m2's capture is transformed as follows:

  • if the enclosing lambda m1 captures by copy, m2 is capturing the non-static member of m1's closure type, not the original variable or this.
  • if the enclosing lambda m1 captures by reference, m2 is capturing the original variable or this.

    #include <iostream>
    
    int main()
    {
    int a = 1, b = 1, c = 1;
    
    auto m1 = [a, &b, &c]() mutable {
        auto m2 = [a, b, &c]() mutable {
            std::cout << a << b << c << '\n';
            a = 4; b = 4; c = 4;
        };
        a = 3; b = 3; c = 3;
        m2();
    };
    
    a = 2; b = 2; c = 2;
    
    m1();                             // calls m2() and prints 123
    std::cout << a << b << c << '\n'; // prints 234
    }
    

因此,您正在从封闭的 lambda 中捕获值并修改它,您也需要使其在封闭的 lambda 中可变。

关于c++ - 嵌套的 lambda 和可变关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58472114/

相关文章:

c++ - 使用模板

c++ - FindWindow( ... ) 不是 'finding' 创建的消息窗口

c++ - 为什么这个可变参数模板参数的替换失败了? (在固定参数之前打包)

c++ - 运行时创建的模板类的调用函数

c++ - 我的 Linux 开发项目的 Clang vs GCC

c - 如何编译静态libwebscocket.a

C 程序编译没有错误但不会运行并且没有警告或错误

c++ - 上下文菜单适用于子组件但不适用于父组件

c# - 如何将 C 函数签名转换为 C# 并在 native DLL 中调用该函数?

c++ - 优化二进制增量循环