How does getInstance() work?

前端 未结 2 1408
清歌不尽
清歌不尽 2021-02-08 12:59

Recent I read some C++ code using extensively following getInstance() method:

class S
{
    private:
        int some_int = 0;
    public:
        static S&          


        
2条回答
  •  悲&欢浪女
    2021-02-08 13:12

    This is the so-called Singleton design pattern. Its distinguishing feature is that there can only ever be exactly one instance of that class and the pattern ensures that. The class has a private constructor and a statically-created instance that is returned with the getInstance method. You cannot create an instance from the outside and thus get the object only through said method.

    Since instance is static in the getInstance method it will retain its value between multiple invocations. It is allocated and constructed somewhen before it's first used. E.g. in this answer it seems like GCC initializes the static variable at the time the function is first used. This answer has some excerpts from the C++ standard related to that.

提交回复
热议问题