How does getInstance() work?

前端 未结 2 1409
清歌不尽
清歌不尽 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:17

    Static variable with a function scope is allocated first time the function is called. The compiler keeps track of the fact that is is initialized the first time and avoids further creation during the next visit to the function. This property would be ideal to implement a singleton pattern since this ensures we just maintain a single copy of object. In addition newer compilers makes sure this allocation is also thread safe giving a bonus thread safe singleton implementation without using any dynamic memory allocation. [As pointed out in comments, it is c++11 standard which guarantees the thread safety so do your check about thread safety if you are using a different compiler]

    1) where does the static variable S defined in line(*) allocated in memory? And why it can work like return this?

    There is specific regions in memory where static variables are stored, like heap for dynamically allocated variables and stack for the typical compile time defined variables. It could vary with compilers but for GCC there are specific sections called DATA and BSS segments with in the executable generated by the compiler where initialized and uninitialized static variables are stored.

    2) what if there exist more than one instance of class S, whose reference will be returned?

    As mentioned on the top, since it is a static variable the compiler ensures there can only be one instance created the first time function is visited. Also since it has the scope with in the function it cannot clash with any other instances existing else where and getInstance ensures you see the same single instance.

提交回复
热议问题