2010-02-23 82 views
4

實現此類的正確方法是什麼?Pimpl成語與類成員變量一起使用

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

作爲另一個問題:我認爲你不能親近的功能,如果它在一個無名的命名空間。 – 2010-02-23 23:24:06

回答

4

MyClass是一個單身人士 - 有人稱它爲一個榮耀的全球。一個經常被濫用的模式。使用私人構建函數和一個公共靜態訪問:

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

有關Singleton模式的更多信息,請參見http://en.wikipedia.org/wiki/Singleton_pattern。由於上述方式並非線程安全 – Eld 2010-02-23 23:12:53

+0

@Eld:我想知道爲什麼你提到線程安全性,直到我遇到OP的另一個問題... – dirkgently 2010-02-23 23:24:51