簡體   English   中英

重置 boost::shared_ptr 由來自 lambda 的值捕獲

[英]Reset boost::shared_ptr captured by value from lambda

在 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()

gcc-5.2.0 給出的帶有標志 -std=c++14 的錯誤是:

main.cpp: In lambda function:
main.cpp:15:27: error: no matching function for call to 
'std::shared_ptr<main()::Test>::reset() const'

只是在尋找最佳實踐。

在 lambdas [...] 中,通過值捕獲的變量使用 const 限定符 [...]

這句話中缺少的部分是“默認”。

情況並非總是如此。 如果你想在 lambda 中捕獲變量,同時仍然能夠在 lambda 中修改它們,你可以在參數列表的末尾添加mutable關鍵字,如下所示:

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

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

也就是說,我必須提到這在提供的代碼中似乎完全沒有必要,因為在 lambda 范圍的末尾,您的共享指針無論如何都會被銷毀,因為您是通過復制而不是通過引用捕獲它的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM