I was wondering if it is ok to call promise.get_future(), move that future somewhere else (e.g. into a vector) and possibly let the promise die before even the future.get() is called. 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!
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;
}
}
std::make_shared
which may be a bit more efficient at creating new objects that will be stored in astd::shared_ptr
(allocates enough memory for the object and the control block in one shot) and covers an edge case regarding exception safety. It also saves on repetition, you can writeauto shared_promise_ptr = std::make_shared<std::promise<bool>>();
. – Antibody