私有构造函数和 make_shared

use*_*038 5 c++ shared-ptr

我有一个带有私有构造函数的单例类。在静态工厂方法中,我执行以下操作:

shared_ptr<MyClass> MyClass::GetInstance()
{
    static once_flag onceFlag;

    call_once(onceFlag, []() {
        if (_instance == nullptr)
            _instance.reset(new MyClass());
    });

    return _instance;
}
Run Code Online (Sandbox Code Playgroud)

如果我使用

_instance = make_shared<MyClass>();
Run Code Online (Sandbox Code Playgroud)

该代码无法编译。我的问题是:为什么new可以调用私有构造函数却make_shared不能?

Ric*_*ges 4

  1. 如前所述,std::make_shared或其组成部分无权访问私有成员。

  2. 和是不必要的call_onceonce_flag它们隐含在 c++11 静态初始化中,

  3. 您通常不想公开共享指针。

 

class MyClass
{
    MyClass() {}

public:
    static MyClass& GetInstance()
    {
        static auto instance = MyClass();
        return instance;
    }
};
Run Code Online (Sandbox Code Playgroud)

然而,我可以想象在一种情况下,您希望公开一个指向 impl 的共享指针 - 在这种情况下,类可以选择“中断”或“重置”该 impl 到一个新的。在这种情况下,我会考虑这样的代码:

class MyClass2
{
    MyClass2() {};

    static auto& InternalGetInstance()
    {
        static std::shared_ptr<MyClass2> instance { new MyClass2 };
        return instance;
    }

public:

    static std::shared_ptr<MyClass2> GetInstance()
    {
        return std::atomic_load(std::addressof(InternalGetInstance()));
    }

    static void reset() {
        std::atomic_store(std::addressof(InternalGetInstance()),
                        std::shared_ptr<MyClass2>(new MyClass2));

    }  
};
Run Code Online (Sandbox Code Playgroud)

然而,最后,我认为类的“静态性”应该是一个实现细节,对于类的用户来说并不重要:

#include <memory>
#include <utility>

class MyClass
{
    // internal mechanics

    struct Impl {

        auto doSomething() {
            // actual implementation here.
        }
    };

    // getImpl now becomes the customisation point if you wish to change the
    // bahviour of the class later
    static Impl& getImpl() {
        static auto impl = Impl();
        return impl;
    }


    // use value semantics - it makes for more readable and loosely-coupled code
public:
    MyClass() {}

    // public methods defer to internal implementation

    auto doSomething() {
        return getImpl().doSomething();
    }
};


int main() {

    // note: just create objects
    auto mc = MyClass();
    mc.doSomething();

    // now we can pass the singleton as an object. Other functions don't even
    // need to know it's a singlton:

    extern void somethingElse(MyClass mc);
    somethingElse(mc);
}

void somethingElse(MyClass mc)
{

}
Run Code Online (Sandbox Code Playgroud)