在同一线程的同一实例上多次调用 shared_future::get() 是否合法?

Is it legal to call shared_future::get() multiple times on the same instance in the same thread?

我找不到关于此事的直接证实或反驳。所有答案似乎都针对 "access from multiple threads" 方面,而不是重复访问本身。

标准是否定义了 std::shared_future 的行为? boost::shared_future 呢?

std::shared_future<T>::valid

中的每个 cppreference

Unlike std::future, std::shared_future's shared state is not invalidated when get() is called.

这是有道理的。如果不是这种情况,那么您将无法让多个线程调用 get。我们可以通过查看标准进一步支持这一点。在 [futures.unique.future]/15 中,他们明确声明 get 仅适用于

releases any shared state ([futures.state]).

而在 [futures.shared.future]/18 中它没有声明这样的事情,因此在调用 get 之后状态仍然有效。


boost::shared_future 具有相同的行为。 Per the reference get 没有文本说明它在调用 get 时使共享状态无效,因此您可以多次调用它。

据我所知这是合法的。 std::shared_future<T>::get() says:

The behavior is undefined if valid() is false before the call to this function.

要去 std::shared_future<T>::valid() it says:

Checks if the future refers to a shared state.

...

Unlike std::future, std::shared_future's shared state is not invalidated when get() is called.

这将使来自同一线程和同一实例的多个 get() 调用有效。