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<Demo> getInstance(){
static shared_ptr<Demo> 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<Demo>::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?