c++ - 通过值可变捕获的 lambda 不适用于 const &?

标签 c++ c++11 lambda

考虑以下几点:

void test( const int &value )
{
    auto testConstRefMutableCopy = [value] () mutable {
        value = 2; // compile error: Cannot assign to a variable captured by copy in a non-mutable lambda
    };

    int valueCopy = value;
    auto testCopyMutableCopy = [valueCopy] () mutable {
        valueCopy = 2; // compiles OK
    };
}

当我将 lambda 声明为可变并按值捕获 value 时(我认为是复制了它),为什么第一个版本会出现编译错误?

使用 clang (x86_64-apple-darwin14.3.0)(错误消息的来源)和 Visual C++ (vc120) 进行测试。

最佳答案

[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. [..]

您的 lambda 中 value 的类型是 const int,因为它是通过从 const int& 复制捕获的。

因此,即使 lambda 的调用运算符函数不是 const(您将 lambda 标记为 mutable),实际的隐式成员 valueconst int 类型,不能被变异。

坦率地说,这似乎很荒谬;我希望这条规则说被引用的类型失去了 constness,因为它是一个拷贝。 lambda 本身是否存在 mutable 关键字(因此,生成的调用运算符函数上是否存在 const 关键字)应该是唯一的访问控制在这里。

在 C++14 中,您可以通过捕获为 [value=value] 来解决此问题,它使用与 auto 相同的规则,因此会删除 常量。 C++ 很棒,不是吗?

关于c++ - 通过值可变捕获的 lambda 不适用于 const &?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31485041/

相关文章:

c++ - Qt - QTcpserver 工作不正常

c++ - 使用模板化是否为带有自定义键的 unordered_map/set 制作了一个好的模式

C++ TensorFlow SoftmaxCrossEntropWithLogits 返回(成本,梯度),如何访问成本?

c++ - 宏导入外部函数

使用自己的线程运行的 C++11 packaged_task 需要一个 join() 才能获得 future

java - Java 流中缺少返回语句

c++11 - 优于 O(n!) 无序元组比较算法

c++ - 模板函数在模板对象上执行成员回调而不提供它的实例

python - "SyntaxError: non-keyword arg after keyword arg"尝试将函数绑定(bind)到 tkinter 中的按钮时

java - ()->System.out.println ("done") 是什么意思?