[英]Is it ok to destroy a std::promise before future.get() is called?
I was wondering if it is ok to call promise.get_future(), move that future somewhere else (eg into a vector) and possibly let the promise die before even the future.get() is called. 我想知道是否可以调用promise.get_future(),将未来移到其他位置(例如,放入向量),并可能甚至在调用future.get()之前让诺言死亡。 In the following example, the call
gateway->refreshWithCallback
executes the lambda in a thread so that the shared pointer may set the promise free even if in the second loop the future.get() was not called yet, which seems to work but I am angsty! 在下面的示例中,调用
gateway->refreshWithCallback
在线程中执行lambda,以便即使第二个循环中未调用future.get(),共享指针也可以将promise设置为free,这似乎可行,但是我好生气!
std::vector<std::future<bool>> futures;
for(GuiGateway *gateway : gateways){
std::shared_ptr<std::promise<bool>> shared_promise_ptr(new std::promise<bool>());
futures.push_back(shared_promise_ptr.get()->get_future());
gateway->refreshWithCallback([shared_promise_ptr](bool success){
shared_promise_ptr.get()->set_value(success);
});
}
qDebug() << "waiting for futures";
for(std::future<bool> &future : futures){
if(future.get() == false){
qDebug() << "error retrieving all gateway data, aborting auto config";
return;
}
}
If you provide a value to the std::promise
before destroying it, the associated std::future
will be able to retrieve it just fine. 如果您在销毁前为
std::promise
提供了一个值,则关联的std::future
将能够很好地对其进行检索。 It does not depend on std::promise
still existing. 它不依赖于
std::promise
仍然存在。 If you failed to provide a value to std::promise
before destroying it, trying to get a result from the std::future
will throw std::future_error
but it is also well defined. 如果您在销毁
std::promise
之前未能为其提供值,则尝试从std::future
获取结果将引发std::future_error
但定义也很明确。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.