user5667542 user5667542 - 1 year ago 72
C++ Question

When does a constructor of a class with static members runs in C++?

I'm new to c++ so i don't know much about it yet

so basically i have this code

header file

class Application{
static Application& getInstance()
return *mInstance;
void run();
static Application* mInstance;

source file

Application* Application::mInstance;
mInstance = this;

then i do


When does the constructor for Application class runs?

It seems to work in visual studio.
So my question is why does this work?

Why does getInstance does not return a null pointer? since i have never instantiated the class.

Is this code standard?

will this work on any modern c++ compiler?

Answer Source

The constructor of a class belongs to an object, i.e. if it is called explicitly by the code somewhere it creates an object in the memory (on the stack or on the heap). So if you do not call the constructor somewhere it is never executed.

I see only the point why this can run is that you did not specify the initial value of the mInstance pointer. This means that its value is undefined and accidentally can have some valid address. If the run() method does not touch the mInstance object itself your code can run sometimes but sometimes not. This is the problem of uninitialized variables in C++.

But I suggest to follow the right singleton pattern: 1. Initialize mInstance as a nullptr. 2. The getInstance() function should call the constructor if mInstance is nullptr.

(Just a general hint: Avoid passing this in constructor to somewhere else because at that point the object is not fully constructed and in case of multi-thread application it can cause issues.)