gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:56:27 25 4
gpt4 key购买 nike

在 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 theconst 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com