谁负责期货和承诺的共享状态 [英] Who is responsible for the shared state of futures and promises

查看:50
本文介绍了谁负责期货和承诺的共享状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁拥有期货和承诺中的共享状态?特别是谁负责这些类中共享状态的构造和删除?还是应该对共享状态进行引用计数?我无法通过阅读有关cppreference的文档来获得答案。

Who owns the shared state in futures and promises? In particular who is responsible for the construction and deletion of the shared state in these classes? Or is the shared state supposed to be reference counted? I am not able to get an answer by reading the docs for these on cppreference.

我想到的最简单的方法是拥有 std :: promise 类负责创建共享状态,然后将其交给从 std :: promise <获取的 std :: future / code>用于在破坏未来时删除。但是,此方法可能导致悬空承诺对象。因此,我不确定这两个国家之间应该如何真正共享状态。

The way I was thinking about it the easiest thing to do would be to have the std::promise class be responsible for the creation of the shared state, but then hand it off to the std::future that is fetched from the std::promise for deletion when the future is destroyed. But then this approach can lead to dangling promise objects. So I am not sure how really the state is supposed to be shared between the two.

例如,下面的代码是否会产生未定义的行为(因为共享状态可能会在破坏未来时被破坏)?

For example does the code below produce undefined behavior (since the shared state might be destroyed when the future is destroyed)?

auto prom = std::promise<void>{};
{
    auto fut = prom.get_future();
}
prom.set_value();

此外,文档 std :: promise ::〜promise 在cppreference上说如果共享状态就绪,则释放它,这使我认为共享状态未计算引用。

Further, the docs for std::promise::~promise on cppreference say "if the shared state is ready, releases it" which gets me to think that the shared state is not reference counted.

推荐答案

std :: future (或 std :: promise )被销毁,它释放其共享状态

When the std::future (or std::promise) is destroyed, it releases its shared state.

此规则指出,当说异步返回对象或异步提供程序释放其共享状态时,它将放弃对共享状态的引用。

This rule states that when an asynchronous return object or an asynchronous provider is said to release its shared state, it gives up its reference to the shared state.

如果该引用是最后一个引用,则共享状态将被破坏。

If that reference was the last one, the shared state is destroyed.

是的,共享状态似乎是引用计数,不,因为 prom ,您的代码示例不会产生UB仍然拥有对共享状态的引用。

So yes, shared state seems to be reference counted and no, your code example does not produce UB since prom still holds a reference to the shared state.

这篇关于谁负责期货和承诺的共享状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆