c++ - 在 lambda 中没有按值分配拷贝

标签 c++ lambda c++11 clang

有人可以向我解释为什么以下内容不起作用(testblub 中的 const)。由于 test 是按我假设的值复制的,我可以设置它,因为它是本地仿函数。

#include <memory>

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

    return 0;
}

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

最佳答案

因为lambdas的operator()默认是const。您需要使用 mutable 关键字使其成为非常量:

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

关于c++ - 在 lambda 中没有按值分配拷贝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10866087/

相关文章:

c++ - 多个序列上的 runAction

c++ - Nsight Eclipse 找不到共享库

lambda - Rspec 模拟 : mock/yield the block from a method call

c++ - 使用 Boost::spirit 编写的解析器的性能问题

c++ - 函数指针默认为 NULL 吗?

c++ - "Entities with the same name defined in an outer scope are hidden"不成立

c++ - GoogleTest Framework 似乎不适用于 Lambda 函数(跟进)

java - 参数返回 void 的可调用/可运行/函数?

c++ - 创建 Qml/C++ 应用程序作为插件

c++ - 将指向类的指针设置为 0 时出现错误 : does not name a type,