考虑以下几点:
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
),实际的隐式成员 value
是const int
类型,不能被变异。
坦率地说,这似乎很荒谬;我希望这条规则说被引用的类型失去了 const
ness,因为它是一个拷贝。 lambda 本身是否存在 mutable
关键字(因此,生成的调用运算符函数上是否存在 const
关键字)应该是唯一的访问控制在这里。
在 C++14 中,您可以通过捕获为 [value=value]
来解决此问题,它使用与 auto
相同的规则,因此会删除 常量
。 C++ 很棒,不是吗?
关于c++ - 通过值可变捕获的 lambda 不适用于 const &?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31485041/