Pimpl

Last-modified: 2013-11-08 (金) 16:42:08
  • Pimpl = ponter to implementation
  • インターフェースと実装を分けるとこで、実装内容を隠蔽
  • 実装部に必要な(依存性のある)ヘッダファイルをcppに移動することで、結合度を削減
  • Pimplオブジェクトのバイナリ表現を変更せずに実装部を大きく変更できる
  • hoge.h
    #ifndef
    #define
    
    #include
    #include
    #include
    
    // インターフェース
    class Hoge{
    public:
    	explicit Hoge(const std::string& str);
    	~Hoge();
    	void func();
    private:
    	Hoge(const Hoge&); // コピー禁止
    	const Hoge &operator =(const Hoge&); // 代入禁止
    	class Impl; // 実際の実装内容
    	std::shared_ptr<Impl> spImpl;
    };
    #endif
  • hoge.cpp
    #include
    
    // 実装
    class Hoge::Impl{
    private:
    	std::string str;
    public:
    	explicit Impl(const std::string& str_):str(str_){}
    	~Impl(){}
    	void func(){ std::cout << str << std::endl; }
    };
    
    Hoge::Hoge(const std::string& str)
    		:spImpl(std::make_shared<Impl>(str)){}
    
    Hoge::~Hoge(){}
    
    void Hoge::func(){ spImpl->func(); }
  • main.cpp
    #include
    
    int main(){
    	Hoge hoge("poyo");
    	hoge.func();
    	return 0;
    }

継承をどうするか

  • 継承するような場面が思いついたら考えてみる