简体   繁体   中英

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{
    public:
        static Application& getInstance()
        {
            return *mInstance;
        }
        Application();
        void run();
        protected:          
        static Application* mInstance;

source file

Application* Application::mInstance;
Application::Application()
    {
        mInstance = this;           
    }

then i do

 Application::getInstance().run();

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?

The constructor of a class belongs to an object , ie 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.)

The constructor is executed whenever an object is constructed.

Static objects at file scope are constructed before calling main() . However, if you are relying on order of construction of two such static objects (eg construction of one relies on the other already being constructed) you potentially have a problem. The order of construction of statics defined in two distinct compilation units (aka source files) is unspecified.

Static objects that are local (eg to a function) are constructed as control passes through their declaration .... typically as their function is called for the first time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM