通过可变值进行lambda捕获不适用于const&amp ;? [英] lambda capture by value mutable doesn't work with const &?

查看:62
本文介绍了通过可变值进行lambda捕获不适用于const&amp ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下内容:

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时(我认为是它的副本),为什么第一个版本会产生编译错误?

Why is the first version a compile error when I've declared the lambda as mutable and captured value by value (which I thought made a copy of it)?

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

Tested with clang (x86_64-apple-darwin14.3.0), which is where the error message comes from, and Visual C++ (vc120).

推荐答案

[C++11: 5.1.2/14]: 如果某个实体是隐式捕获的,并且 capture-default = >如果使用不包含& 的捕获显式捕获了它.对于每个通过副本捕获的实体,在闭包类型中声明一个未命名的非静态数据成员.这些成员的声明顺序未指定. 如果实体不是对对象的引用,则此类数据成员的类型为相应捕获的实体的类型,否则为引用的类型. [..]

lambda内部的value类型为const int,因为它是通过const int&的副本捕获的.

The type of value inside your lambda is const int, because it was captured by copy from a const int&.

因此,即使lambda的调用运算符功能不是const(已将lambda标记为mutable),实际的隐式成员value的类型也为const int,并且无法进行突变.

Thus, even though the lambda's call operator function is not const (you marked the lambda mutable), the actual implicit member value is of type const int and cannot be mutated.

坦率地说,这似乎很荒唐;我希望这条规则可以说所引用的类型失去了const ness,因为它是副本. lambda本身上是否存在mutable关键字(因此,所生成的调用运算符上是否存在const关键字)应该是这里唯一的访问控制.

Frankly, this seems absurd; I would expect this rule to say that the referenced type loses constness, as it's a copy. The presence or absence of the mutable keyword on the lambda itself (and, thus, the presence or absence of the const keyword on the generated call operator function) should be the only access control here.

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

In C++14 you can work around this by capturing as [value=value], which uses the same rules as auto and thus drops the const. C++'s great, ain't it?

这篇关于通过可变值进行lambda捕获不适用于const&amp ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆