0

Here is the example code snippet:

#include<future>
#include<iostream>

int main()
{
    auto f=[](){
        std::promise<int> promise_;   //Since `promise_` is a local variable, is there any potential problem?
        auto future_ = promise_.get_future();
        promise_.set_value(1);

        return future_;
    }();

    std::cout << f.get() << std::endl;
}
John
  • 2,963
  • 11
  • 33
  • 1
    I asked the same question here: [Is it okay for std::future to outlive a std::promise?](https://stackoverflow.com/questions/58811371/is-it-okay-for-stdfuture-to-outlive-a-stdpromise) – jtbandes Oct 18 '22 at 03:54
  • @jtbandes Sorry, I can't the said post could answer my question. – John Oct 18 '22 at 06:11
  • I don't see any problem here. Once the `promise_` is destroyed, it just releases the shared state. The shared state still exists, since it has been associated with `future_` (and this association is then moved to `f`). – Daniel Langr Oct 18 '22 at 06:23
  • @Daniel Langr You say that once the promise_ is destroyed, it just releases the shared state. So I think you mean the shared state does not exist anymore. But in the next sentence, you say the shared state still exists, since it has been associated with future_. I am really confused. – John Oct 18 '22 at 06:26
  • @John Releasing the shared state by a promise doesn't imply that the shared state "does not exist anymore". Look to the [documentation](https://en.cppreference.com/w/cpp/thread/promise): _"If this was the last such reference, the shared state is destroyed."_ This does not apply here, since the future object _references_ the shared state as well. – Daniel Langr Oct 18 '22 at 06:28

0 Answers0