Pimpl习语与类成员变量一起使用

时间:2010-02-23 23:02:17

标签: c++ pimpl-idiom

实现这门课的正确方法是什么?

//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()
{
  //...
}

1 个答案:

答案 0 :(得分:4)

MyClass是一个单身人士 - 有人称之为荣耀的全球。经常被滥用的模式。使用私有ctors和公共静态访问器:

 MyClass {
       public:
            static MyClass& Instance() {
                 static MyClass obj;
                 return obj;
            }
       // ...
       private:
            MyClass() : m_handle(pimpl()), initialized(true) {}
       // ...
 };