如何在lamda中通过引用捕获unique_ptr正常工作?

问题描述 投票:0回答:1

在一个功能中,我有这个:

void main() {
  auto poller = std::make_unique<Poller>();
  auto polling_func = [&poller] {
    poller->Poll();
  };
  // assume foo signature is correct for passing
  if (condition) foo(std::move(polling_func));
  else foo(std::move(some_other_func));
  // other things happen
  poller->DoSomethingElse(); // this is why I cannot move poller completely inside the lamda
  return;
}

稍后,在polling_func中调用foo。该程序可以编译并正确运行。但是,我对通过引用捕获lamda中的unique_ptr感到非常讨厌。这是如何在后台进行的,我该怎么做?

C++17一起使用GCC 9

c++ c++17 smart-pointers unique-ptr
1个回答
2
投票

但是,我对于通过引用捕获lamda中的unique_ptr感到非常讨厌。

只要您确保所捕获的对象的寿命超过了lambda的寿命,这没有什么错。

适用于由lambda引用捕获的任何对象。

© www.soinside.com 2019 - 2024. All rights reserved.