4

Whats the correct way of implementing this class?

//Header
#include <boost/shared_ptr.hh>

class MyClass
{
public:

    static foo()
    static foobar();

private:
    class pimpl;
    static boost::shared_ptr<pimpl> m_handle;
    static bool initialized;
};


//source
namespace
{
  bool init()
  {
     //...
     // init() can't access m_handle, unless it is a friend of MyClass
     // but that seems a bit "tacky", is there a better way?
  }
}


class MyClass::pimpl
{
   public:
      ~pimpl(){}
}    


bool MyClass::initialized = init();

MyClass::foo()
{
  //...
}

MyClass::foobar()
{
  //...
}
Marc Mutz - mmutz
  • 24,485
  • 12
  • 80
  • 90
Stick it to THE MAN
  • 5,621
  • 17
  • 77
  • 93

1 Answers1

4

MyClass is a singleton -- some call it a glorified global. An oft-abused pattern. Use private ctors and a public static accessor:

 MyClass {
       public:
            static MyClass& Instance() {
                 static MyClass obj;
                 return obj;
            }
       // ...
       private:
            MyClass() : m_handle(pimpl()), initialized(true) {}
       // ...
 };
dirkgently
  • 108,024
  • 16
  • 131
  • 187
  • 1
    See http://en.wikipedia.org/wiki/Singleton_pattern for more information on the Singleton pattern. As the above way isn't threadsafe – Eld Feb 23 '10 at 23:12
  • @Eld: And I was wondering why you mention thread-safety until I came across the OP's other question... – dirkgently Feb 23 '10 at 23:24