The simple answer to your question is no. As others have pointed out, there are guarantees for objects defined in translation units including <iostream> , at least if the object is defined after inclusion. But that doesnβt always help: you include <iostream> in the translation unit, which defines the constructor, not necessarily which defines the static variable. Therefore, cases such as the following are possible:
file1.hh
class X { public: X(); };
file1.cc
#include "file1.hh" #include <iostream> X::X() { std::cout << "Coucou, me voila!" << std::endl; }
file2.cc
#include "file1.hh" X anX;
In this case, it is possible that the anX constructor is called before std::cout .
To be safe: if the constructor of the object, which can be used as a static variable, wants to use any of the standard threads, this should probably declare a local static type ios_base::Init :
X::X() { static ios_base::Init dummyForInitialization; std::cout << "Coucou, me voila!" << std::endl; }
If std::cout has not yet been constructed when this constructor is called, when the static variable is built.
source share