c++ - 重置由 lambda 值捕获的 boost::shared_ptr

标签 c++ lambda shared-ptr pass-by-value

在 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'

只是寻找最佳实践。

最佳答案

In lambdas [...] variables captured by value are stored using the const qualifier [...]

这句话漏掉的部分是“默认”。

不一定总是这样。如果你想在 lambda 中捕获变量,同时仍然能够在 lambda 中修改它们,你可以在参数列表的末尾添加 mutable 关键字,如下所示:

  class Test {};
  auto testPtr(boost::make_shared<Test>());

  auto lambda1([testPtr]() mutable
               {
                 testPtr.reset();
               });

也就是说,我必须指出,这在所提供的代码中似乎完全没有必要,因为在您的 lambda 范围结束时,您的共享指针无论如何都会被销毁,因为您是通过复制而不是通过引用捕获它的。

关于c++ - 重置由 lambda 值捕获的 boost::shared_ptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33565253/

相关文章:

c# - 如何避免在 lambda 表达式中捕获变量?

C++ 自动检测 shared_ptr 与 NULL 比较的位置

c++ - 为什么 std::weak_ptr<> 不提供 bool 转换?

c++ - 防止虚函数在子类中重载两次

c++ - 自 C++17 起使用 std::launder 到 "validate"非 "pointer to object"指针值

c++ - 我如何为数学公式创建命名空间

c# - 用什么?委托(delegate)、事件或 Func<T>?

java - 从 Factory 重构中提取 lambda(使用 IDE)?

c++ - RAW指针容器包装器

c++ - 为什么在 gcc/libstdc++ 的 __enable_shared_from_this_helper 中没有模板参数