微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c-在调用future.get()之前销毁std :: promise可以吗?

我想知道是否可以调用promise.get_future(),将那个未来移动到其他地方(例如到向量中),并可能甚至在调用future.get()之前让诺言死亡.在下面的示例中,调用网关-> refreshWithCallback在线程中执行lambda,以便即使在第二个循环中未调用future.get()时,共享指针也可以将promise释放为空,这似乎可行,但是我很生气!

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 :: promise提供了一个值,则关联的std :: future将能够很好地对其进行检索.它不依赖于std :: promise仍然存在.如果在销毁std :: promise之前未能提供其值,则尝试从std :: future获取结果将抛出std::future_error,但定义也很明确.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐