1

Suppose that I have 3 .cpp files. A.cpp, B.cpp and C.cpp.
Inside those files there are classes (see code below) and after each class an object is initialized.

File A.cpp.

class A
{
public:
    A()
    {
        std::cout << "A constructor\n";
    }
};

A a;

File B.cpp.

class B
{
public:
    B()
    {
        std::cout << "B constructor\n";
    }
};

B b;

File C.cpp.

class C
{
public:
    C()
    {
        std::cout << "C constructor\n";
    }
};

C c;

Finally, we build using cmake like this:

add_executable(${PROJECT_NAME} src/main.cpp src/A.cpp src/B.cpp src/C.cpp)

I know that the constructor will be called once an object is initialized. In that case, there are 3 objects that are initialized inside a .cpp file.

Is there any predefined order that the objects are initialized, therefore a specific order that the constructors are called?
I know I can run the program and figure it out by myself but I'd like to know if there is any rule that applies to this case.
I'm developing some code for embedded systems and I wanna be sure that I won't run into a race condition.

MrBit
  • 290
  • 4
  • 20
  • There is not. This is what leads to the static initialization order fiasco. Looking for a dupe target – NathanOliver Jul 06 '21 at 15:49
  • 2
    No there is not predefined order that is why there is a chance of [Static Initialization Order Fiasco](https://en.cppreference.com/w/cpp/language/siof). – Marek R Jul 06 '21 at 15:50
  • 2
    *I know I can run the program and figure it out by myself* Running the program will only tell you that the order you see is one possible legal result. But running the program will not tell you that the order you observe is the only permissible order. Or that the order might very well change with the phase of the moon.. – Andrew Henle Jul 06 '21 at 15:51
  • A race condition won't happen since only one thread is involved. – molbdnilo Jul 06 '21 at 16:21
  • @molbdnilo Is it guaranteed in the standard that only one thread is involved during static initialization? AFAIK their is only the guarantee that initialization happens in-order within a single translation unit, but it's otherwise legal to initialize each translation unit in parallel with one-another -- though I may be mistaken – Human-Compiler Jul 06 '21 at 16:25
  • @Human-Compiler I don't think there's an explicit mention of threads during initialization, but there it does say, "Executing a program starts a main thread of execution in which the main function is invoked, and in which variables of static storage duration might be initialized and destroyed" which sounds like only one thread can be used to initialize statics. – 1201ProgramAlarm Jul 06 '21 at 17:19

0 Answers0