[英]Passing a mutable lambda with unique_ptr into a const& std::function
我有一个调度函数,它在主线程中执行给定的lambda。 为了这个问题,假设它看起来如下:
void dispatch(const std::function<void()>& fn) {
fn();
}
我需要在新线程中加载一个新对象而不会中断主线程。 所以我执行以下操作:1)启动一个新线程并在线程内创建一个新的唯一指针,2)调用dispatch
并传播它所属的新唯一指针。
std::unique_ptr<std::string> foo; // nullptr
// do the loading in a new thread:
std::thread t([&](){
// in the new thread, load new value "Blah" and store it temporarily
auto bar = std::make_unique<std::string>("Blah");
dispatch([bar2 = std::move(bar), &foo]() mutable {
foo = std::move(bar2); // propagate the loaded value to foo
});
});
t.join(); // for the sake of this example
std::cout << "foo = " << *foo << std::endl; // this should say: foo = Blah
在线运行示例: http : //cpp.sh/5zjvm
此代码无法编译,因为dispatch
的内部lambda是mutable
,因此不适合需要const&
dispatch(const std::function<void()>& fn)
。
然而,lambda需要是mutable
因为它需要在唯一指针上调用std::move
。
可以修改此代码,例如将dispatch
更改为:
template <typename Fn>
void dispatch(Fn fn) {
fn();
}
不幸的是, dispatch
功能是库的API,我不能改变它。
如果没有摆脱独特的指针,有没有办法摆脱这个问题?
不,那不是你的问题。
你的问题是你的lambda无法复制,因为它有一个由值中捕获的唯一ptr。
std::function<Sig>
类型删除到
用Sig
调用
破坏
复制(有时移动)
铸造回至原来的型
您的lambda无法复制,因此无法存储在std::function
。
懒惰编码器的解决方案是:
dispatch([bar2 = std::make_shared<decltype(bar)>(std::move(bar)), &foo]() mutable {
foo = std::move(*bar2);
});
我们将不可复制的状态推送到shared_ptr
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.