【发布时间】:2016-02-07 12:13:18
【问题描述】:
在 lambda 中,由于按值捕获的变量是使用 const 限定符存储的,因此从 lambda 重置 boost::shared_ptr 的正确方法是什么?
class Test {};
auto testPtr(boost::make_shared<Test>());
// Error: shared_ptr captured with const
auto lambda1([testPtr]()
{
testPtr.reset();
});
// Ok: but "testPtr" could be out of scope once the lambda is called
auto lambda2([&testPtr]()
{
testPtr.reset();
});
我想这也许可行:
auto copyOfTestPtr(testPtr);
auto lambda3([&testPtr, copyOfTestPtr]()
{
// is it guaranteed that the variable referenced by &testPtr
// will exist later on?
testPtr.reset();
});
// this reference is not necessary anymore so decrement shared_ptr counter
// (the lambda still having a copy so the counter won't be zero)
copyOfTestPtr.reset()
带有标志 -std=c++14 的 gcc-5.2.0 给出的错误是:
main.cpp: In lambda function:
main.cpp:15:27: error: no matching function for call to
'std::shared_ptr<main()::Test>::reset() const'
只是在寻找最佳实践。
【问题讨论】:
标签: c++ lambda shared-ptr pass-by-value