pimpl 惯用法

LIZHAO 编程技术
阅读量 0 评论量 0

pimpl 即 Private Implementation(Pointer to Implementation。

通过一个私有的指针,指向类的内部,以实现类的核心数据的隐藏。

pimpl的优点

  1. 隐藏类的核心数据成员和私有函数。
  2. 可加快编译的速度,例如一些复杂的类,引用该类的地方很多,每个引用的地方都要引入头文件
      便会增加编译时间,这种方式,将实现放在了cpp文件中,其他地方在引入这个头文件的时候,
      依赖的类型变少,编译的速度加快。
  3. 接口和实现分离,我们导出的头文件,仅仅包含一个pimpl的指针,当我们对pimpl类进行修改时
      导出的头文件不需要修改。

一个简单的实例

Loading...
载入代码中...
//pimpl_usage.h class PImplUsage { public: PImplUsage(); ~PImplUsage(); void printNumber(); void printString(); //调用了隐藏的类成员函数。 void printStringPublic(); private: //隐藏了,类的具体的成员变量和私有函数。 class Impl; Impl * m_pimpl; };
Loading...
载入代码中...
//pimpl_usage.cpp #include "pimpl_usage.h" #include <iostream> class PImplUsage::Impl { public: Impl() { //初始化工作,例如初始化成员变量等。 m_number = 0; m_ptr = new char[20]{"hello world!"}; } ~Impl() { //一些清理工作 delete[] m_ptr; } void printStringPrivate(); public: int m_number; char *m_ptr; }; void PImplUsage::Impl::printStringPrivate() { std::cout << "hello world private!!!" << std::endl; } void PImplUsage::printNumber() { std::cout << m_pimpl->m_number << std::endl; } void PImplUsage::printString() { std::cout << m_pimpl->m_ptr << std::endl; } PImplUsage::PImplUsage() { m_pimpl = new Impl(); } PImplUsage::~PImplUsage() { delete m_pimpl; } void PImplUsage::printStringPublic() { m_pimpl->printStringPrivate(); }
喵~