C++ lambda 通过父 lambda 捕获值的副本捕获

C++ lambda capturing by copy of parent lambda's captured value

正在尝试编译以下代码:

#include <functional>

void test() {

    int a = 5;

    std::function<void()> f = [a](){
        [a]()mutable{ // isn't it capture 'a' by copy???
            a = 13; // error: assignment of read-only variable 'a'
        }();
    };

}

给出 error: assignment of read-only variable 'a' 错误。

通过添加花括号来更改代码 a 捕获:

#include <functional>

void test() {

    int a = 5;

    std::function<void()> f = [a](){
        [a{a}]()mutable{ // this explicitly copies a
            a = 13; // error: assignment of read-only variable ‘a’
        }();
    };

}

消除编译错误。 我想知道为什么会这样?第一个变体不等同于第二个吗?

这是在使用来自 Debian 的 g++ 版本 8.3.0 时。

clang++7.0.1版本编译成功

g++ 中的错误?

[C++11: 5.1.2/14]: An entity is captured by copy if it is implicitly captured and the capture-default is = or if it is explicitly captured with a capture that does not include an &. For each entity captured by copy, an unnamed non-static data member is declared in the closure type. The declaration order of these members is unspecified. The type of such a data member is the type of the corresponding captured entity if the entity is not a reference to an object, or the referenced type otherwise.

你的 mutable lambda 中 a 的类型是 const int 因为它是通过从包含 constlambda。因此,使两个 lambda 都可变可以解决这个问题。