Private constructor and make_shared

后端 未结 3 1561
生来不讨喜
生来不讨喜 2021-01-06 20:34

I have a singleton class with a private constructor. In the static factory method I do the following:

shared_ptr MyClass::GetInstance()
{
             


        
3条回答
  •  抹茶落季
    2021-01-06 21:21

    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;
    }
    

提交回复
热议问题