在一个功能中,我有这个:
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
但是,我对于通过引用捕获lamda中的
unique_ptr
感到非常讨厌。
只要您确保所捕获的对象的寿命超过了lambda的寿命,这没有什么错。
适用于由lambda引用捕获的任何对象。