在 lambda 中通过引用捕获 unique_ptr 如何正常工作?
How does capturing unique_ptr by reference in lambda work correctly?
在一个函数中我有这个:
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;
}
稍后在foo
中调用了polling_func
。该程序可以正确编译和运行。但是,我对通过引用在 lamda 中捕获 unique_ptr
感到非常厌恶。这是如何在幕后工作的,我应该这样做吗?
将 C++17
与 GCC 9
结合使用
However I am feeling really icky about capturing the unique_ptr
in lamda by reference.
只要您确保捕获的对象在 lambda 的生命周期之后仍然存在,这就没有问题。
这适用于通过 lambda 引用捕获的任何对象。
在一个函数中我有这个:
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;
}
稍后在foo
中调用了polling_func
。该程序可以正确编译和运行。但是,我对通过引用在 lamda 中捕获 unique_ptr
感到非常厌恶。这是如何在幕后工作的,我应该这样做吗?
将 C++17
与 GCC 9
However I am feeling really icky about capturing the
unique_ptr
in lamda by reference.
只要您确保捕获的对象在 lambda 的生命周期之后仍然存在,这就没有问题。
这适用于通过 lambda 引用捕获的任何对象。