我有一个具有以下结构的单例:
// 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
。我必须这样做,因为 mManager1
和 mManager2
在 ctor 中的用途中使用了 mInstance
。
问题是如何将this
与boost::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/