Boost logo

Boost Users :

Subject: Re: [Boost-users] shared_ptr singleton
From: Peter Dimov (pdimov_at_[hidden])
Date: 2008-10-16 18:42:06


Alessandro Re:
...
> class Register;
> typedef shared_ptr<Register> RegisterP;
> class Register: public Object {
> public:
> Register();
> void add(string name) {
> // Stuff with name
> }
> static RegisterP global() {
> if (!_global) _global = RegisterP(new Register); // *
> return _global;
> }
> private:
> static RegisterP _global;
> };

...

> Yes, I'm defining it with:
> RegisterP Register::_global;
> This should invoke the default constructor, right?

The problem is that the default constructor may be invoked after the first
call to Register::global, overwriting _global and resetting it to empty. The
first subsequent call to global() would now reinitialize it.

You can avoid this by making _global a local static:

static RegisterP global()
{
    static RegisterP _global( new Register );
    return _global;
}


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net