编码规范-C++:不要使用 [=] 默认捕获

编号

F.54

标题

在编写捕获 this 指针或任何类数据成员的 lambda 表达式时,不要使用 [=] 默认捕获

语言

C++

级别

5

类别

函数

规范说明

这是 C++ 核心指南中的一条规则,关于规则 F.54 的更多细节,请参见 C++ 核心指南页面。

原因:这会造成混淆。在成员函数中使用 [=] 看似是值捕获,但实际上是通过引用捕获数据成员,因为它实际上是通过值捕获了不可见的 this 指针。如果你有意这么做,请明确写出 this。

示例

class My_class {
    int x = 0;
    // ...

    void f()
    {
        int i = 0;
        // ...

        auto lambda = [=] { use(i, x); };   // BAD: "looks like" copy/value capture
        // [&] has identical semantics and copies the this pointer under the current rules
        // [=,this] and [&,this] are not much better, and confusing

        x = 42;
        lambda(); // calls use(0, 42);
        x = 43;
        lambda(); // calls use(0, 43);

        // ...

        auto lambda2 = [i, this] { use(i, x); }; // ok, most explicit and least confusing

        // ...
    }
};

注意:如果你打算捕获所有类数据成员的副本,请考虑使用 C++17 的 [*this]。

执行:标记任何指定了 [=] 捕获列表默认捕获,并且也捕获了 this(无论是显式捕获还是通过默认捕获并在函数体内使用了 this)的 lambda 表达式。

原文链接:,转发请注明来源!