没有在lambda中按值分配副本

abe*_*ier 3 c++ lambda clang c++11

有人可以向我解释为什么以下不起作用(testconst里面blub).因为test是我假设的值复制,我可以设置它,因为它是functor local.

#include <memory>

int main()
{
    std::shared_ptr<bool> test;
    auto blub = [test]() {
        test = std::make_shared<bool>(false);
    };

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

为了使这个工作,首先我必须引入一个新的shared_ptr,分配test,然后我通常可以分配另一个shared_ptr.顺便说一句:我正在使用clang 3.1

R. *_*des 7

因为operator()lambda是const默认的.您需要使用mutable关键字使其成为非const:

auto blub = [test]() mutable {
    test = std::make_shared<bool>(false);
};
Run Code Online (Sandbox Code Playgroud)