0

I have a singleton with a following structure:

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

The idea is to remove instance automatically when program exists. Look at line marked [!!!] : mInstance = this. I have to do this because mManager1 and mManager2 are using mInstance in their purposes in ctor.

The problem is how to use this with boost::scoped_ptr? In shared_ptr case there is enable_shared_from_this class from boost which allows to get what I need. But what to do in my case?

Max Frai
  • 61,946
  • 78
  • 197
  • 306

1 Answers1

1

You can simply have the constructors take the Root as argument, and then pass this to them:

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

One additional advantage of this is that you don't get the other classes coupled to the singleton secretly.

R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510
  • Okay, thanks. It's a good idea, I'll do everything this way. But I'm still interested what to do in my case? – Max Frai Jan 24 '12 at 20:37