c++promisestdfuture

std::future with temporary std::promise


I have a problem with understanding how the promise cooperates with future. I have a function that is returning std::future like in this example:

std::future<int> calcSomeValue() {
}

My problem is that this future can be either calculated asynchronously spawning a thread, or can have a result already ready to return, so I would like to have it returned using std::promise without running a thread. But... I don't know if this is safe or not or what else could I do. See example:

std::future<int> calcSomeValue() {
    if (resultIsReady()) {
        std::promise<int> promise; // on the stack
        std::future<int>  rv = promise.get_future(); // is future part of the memory occupied by promise?

        promise.set_value(resultThatIsReady); // does it store the value in promise or in future?
        return rv; // <--- What will happen when promise is lost?
    }
    else {
        return std::async(....)
    }
}

See the comment in the code above. Is future accessing promise variable when .get() is called, where promise is already fulfilled? If it is then I will have a big doo doo here.

Can anyone advise me how can I return std::future in this particular case?


Solution

  • A promise-object is associated with a shared state (note the "shared"). When calling promise::get_future, you'll receive a future- object associated with the same shared state as the one with which the respective promise object is associated. This state will live at least as long as one associated producer (i.e. the promise) or a consumer (i.e. the future) lives. Hence, it does not matter if the promise's lifetime ends before the corresponding future-object.

    Not normative, but see, for example, promise as described at cplusplus.com:

    The lifetime of the shared state lasts at least until the last object with which it is associated releases it or is destroyed. Therefore it can survive the promise object that obtained it in the first place if associated also to a future.