Is std::cout guaranteed to be initialized?

The answer differs depending on if you’re using C++03 or C++11.

In C++11, your code is guaranteed to work, but in C++03 it’s unspecified; your only guarantee is that by the time main() is entered, the standard streams had been initialized. (That said, all mainstream implementations initialize them prior to running any dynamic initialization, making them fine to use.)

You can force initialization by constructing an std::ios_base::Init object, like so:

#include <iostream>

struct test
{
    test() { std::cout << "test::ctor" << std::endl; }
    ~test() { std::cout << "test::dtor" << std::endl; }

private:
    std::ios_base::Init mInitializer;
};

test t;

int main()
{
    std::cout << "Hello world" << std::endl;
    return 0;
}

Now when test constructs, it initializes mInitializer and guarantees the streams are ready to use.

C++11 fixed this slightly annoying behavior by acting as if every instance of #include <iostream> were followed by static std::ios_base::Init __unspecified_name__;. This automatically guarantees the streams are ready to use.

Leave a Comment