I have a function that returns a reference to a std::promise:
std::shared_ptr<std::promise<void>> play();
(More info: The function plays media on some device, and the return value represents when this playing is complete. If play is called a second time, a value is set on the promise returned the first time, and a new promise is created and returned for this second call)
The caller can then catch the value and wait on the future:
auto this_future = play()->get_future();
this_future.wait();
Does it make sense to return a reference to the promise, or should I return the future instead, so that the calling function does not have to call get_future()?
Since the implementation of play()
is not posted, I'd say most likely you should return the future, and the function should work with the promise itself, most likely in a different thread. The rationale for this design stems from the fact that promise is a producer end, and future is a consumer end — so the function would produce a value, set it through the promise instance, which will notify the future that result has arrived through get
.
However, note that, you don't have to return a std::shared_ptr<std::future<T>>
— just std::future<T>
would work great.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With