Home > Software design >  Can std::future cause coredump without get or wait
Can std::future cause coredump without get or wait

Time:05-27

void func() {
    std::future<int> fut = std::async(std::launch::async, []{
        std::this_thread::sleep_for(std::chrono::seconds(10));
        return 8; 
    });
    return;
}

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?

CodePudding user response:

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.

  • Related