有人可以向我解释为什么以下内容不起作用(test
是 blub
中的 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/