Singleton class implementation using shared_ptr

前端 未结 3 1310
遇见更好的自我
遇见更好的自我 2021-02-09 17:58
#include 
#include 

using namespace std;

class Demo {
    static shared_ptr d;
    Demo(){}
public:    
    static shared_ptr         


        
3条回答
  •  耶瑟儿~
    2021-02-09 18:29

    This is not thread-safe: two threads calling getInstance would cause a data race. A common approach is to use a function-scope static variable:

    static shared_ptr getInstance(){
      static shared_ptr d(new Demo);
      return d;
    }
    

    Such a variable is guaranteed to be initialized exactly once, when control passes over its definition for the first time, and in a thread-safe manner.

    At this point though, it's not at all clear why you would want to use shared_ptr. You could just as well do

    static Demo& getInstance(){
      static Demo d;
      return d;
    }
    

    This is a textbook implementation of a singleton (well, one of).


    Re: initialize with a private constructor. I'm not sure I understand the nature of your confusion. Are you asking why Demo::getInstance can use private constructor of Demo? Well, because it's a member of Demo, and members of a class can access private members of that class. Are you asking why Demo::getInstance can call shared_ptr::reset() passing a Demo* pointer? Well, because reset() is a public member function of shared_ptr, taking a pointer as a parameter. Which part of this process do you find controversial?

提交回复
热议问题