【问题标题】:Reset boost::shared_ptr captured by value from lambda重置由 lambda 中的值捕获的 boost::shared_ptr
【发布时间】: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


    【解决方案1】:

    在 lambdas [...] 中,按值捕获的变量使用 const 限定符 [...]

    这句话中缺少的部分是“默认情况下”。

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

      class Test {};
      auto testPtr(boost::make_shared<Test>());
    
      auto lambda1([testPtr]() mutable
                   {
                     testPtr.reset();
                   });
    

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

    【讨论】:

    • 好吧,不知道 mutable!是的,这个想法是 lambda 是指向 Test 对象的最后一个。想象一下从函数返回的 lambda,并且由于 lambda 对象中的 shared_ptr,Test 对象在堆中保持活动状态。
    • @ChrisPeterson 我也编写了这样的设计代码,只是为了确保您仍然不需要重置指针,当您的 lambda 死亡时,您的对象将死亡,lambda 不是永恒的,它们有像所有其他对象一样的生命周期:)
    • 是的,没错。它是用于更好地理解概念的代码而不是用于生产的代码 :) 所有这些的上下文类似于:std::thread( [ioServiceWorkSharedPtr](){} ),当线程完成时,然后重置指针,以便 myIoService .run() 调用可以干净地完成。
    猜你喜欢
    • 2013-10-31
    • 2019-10-10
    • 2014-02-04
    • 2018-06-22
    • 1970-01-01
    • 1970-01-01
    • 2021-10-10
    • 2013-03-29
    • 2010-09-13
    相关资源
    最近更新 更多