Is it ok to destroy a std::promise before future.g

2019-02-24 10:01发布

问题:

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;
    }
}

回答1:

If you provide a value to the std::promise before destroying it, the associated std::future will be able to retrieve it just fine. It does not depend on std::promise still existing. 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.