Daily C++ Puzzle 4

The future nobody kept

A short C++ program with a bug: the future nobody kept. The answer, the observed output, the fix, and the lesson are on this page.

#include <chrono>
#include <future>
#include <iostream>
#include <thread>

int main() {
    auto start = std::chrono::steady_clock::now();
    std::async(std::launch::async, [] {
        std::this_thread::sleep_for(std::chrono::seconds(1));
    });
    auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
        std::chrono::steady_clock::now() - start).count();
    std::cout << "reached next line after " << ms << " ms\n";
}

The discarded temporary future's destructor blocks until the task finishes — so the "fire and forget" call waits a full second. GCC also warns about it (ignoring return value of 'std::async', declared with attribute 'nodiscard').

Observed output: reached next line after 1001 ms.

Fix: store the future (auto fut = std::async(...)) and wait on it deliberately.

Lesson: a discarded std::async future is a join, not a launch.

Facts verified 2026-11-04. The code on this page was compiled and run on the box with GCC 16.2.0 at -std=c++23 -Wall -Wextra; the outputs quoted are the observed outputs. MSVC was not tested.

Back to the daily tips index

Keep Exploring

Keep exploring the docs, samples, and free tools to continue your evaluation.