I have a singleton class with a private constructor. In the static factory method I do the following:
shared_ptr MyClass::GetInstance()
{
Please take VTT's comment seriously.
To your question:
My question is: why new can invoke a private constructor but make_shared not?
The new
is actually used within a lambda in a member-function; Well, A lambda defines a local-class, and C++ standards permits a local-class within a member-function to access everything the member-function can access. And its trivial to remember that member functions can access privates..
std::make_shared
has no access to the privates of MyClass
. It's outside the scope of MyClass
Example:
class X{
X(){};
public:
static X* create(){ // This member-function can access private functions and ctors/dtor
auto lm = [](){ // This lambda inherits the same access of enclosing member-function
return new X();
};
return lm();
}
};
int main(){
auto x = X::create(); //valid;
auto y = new X(); //invalid;
}