Can std::future cause coredump without get or wait

void func() {
    std::future<int> fut = std::async(std::launch::async, []{
        return 8; 

Let’s say that I have such a function. An object fut of std::future<int> is initialized with a std::async job, which will return an integer in the future. But the fut will be immediately released after the function func returns.

Is there such an issue: When the std::async job returns and try to assign the 8 to the object fut, the object has already been released…

If so, a coredump about SIGSEGV may occur…

Am I right about it? Or std::future has some mechanism to avoid this issue?

>Solution :

Futures created with std::async have a blocking destructor that waits for the task to finish.

Even if you instead create a future from std::promise, the docs for ~future() don’t mention the problem you’re asking about.

The docs use the term "shared state" a lot, implying that a promise and a future share a (heap-allocated?) state, which holds the return value, and isn’t destroyed until both die.

Leave a ReplyCancel reply