c++ - 单例实例和 scoped_ptr

标签 c++ boost singleton smart-pointers

我有一个具有以下结构的单例:

// Hpp
class Root : public boost::noncopyable
{
    public:
        ~Root();

        static Root &Get();

        void Initialize();
        void Deinitialize();

    private:
        Root();  // Private for singleton purposes
        static boost::scoped_ptr<Root> mInstance;

        Manager1 *mManager1;
        Manager2 *mManager2;
};


// Cpp
boost::scoped_ptr<Root> Root::mInstance;

Root::Root()
{
    // [!!!]
    mInstance = this;

    // Managers are using `mInstance` in their constructors
    mManager1 = new Manager1();
    mManager2 = new Manager2();

    mInstance->Initialize();
}

Root::~Root() { delete mManager1; delete mManager2; }

Root &Root::Get()
{
    if (mInstance == nullptr) mInstance = boost::scoped_ptr<Root>(new Root());
    return *mInstance;
}

这个想法是当程序存在时自动删除实例。查看标记为 [!!!] 的行:mInstance = this。我必须这样做,因为 mManager1mManager2 在 ctor 中的用途中使用了 mInstance

问题是如何将thisboost::scoped_ptr一起使用?在 shared_ptr 案例中,有来自 boost 的 enable_shared_from_this 类,它允许获得我需要的东西。但是我的情况该怎么办?

最佳答案

您可以简单地让构造函数将 Root 作为参数,然后将 this 传递给它们:

Root::Root() {
    mManager1 = new Manager1(this);
    mManager2 = new Manager2(this);    
    Initialize();
}

这样做的另一个好处是您不会将其他类 secret 地耦合到单例。

关于c++ - 单例实例和 scoped_ptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8993540/

相关文章:

c++ - 使用 boost::serialize 反序列化多个值(使用 SSCCE)

python - 如何在 Python 的静态方法中拥有一个 self 实例

ios - Swift、单例、代表函数的变量

c# - 使用ANTLR用C#解析C++

c++ - std::function 用于方法参数、复制还是shared_ptr?

c - 如何从 time_t/timeval 获取 iso_date ( YYYYMMDD )

c# - 将记录器作为单例是一种好习惯吗?

c++ - 在类中重载函数调用运算符

java - Android 到虚幻引擎接口(interface) (C++)

c++ - 如何取消 boost asio io_service post