C++中的PIMPL设计模式

另一个 Blog 地址: 原文链接:

C++ 中的“柴郡猫技术”(Cheshire Cat Idiom),又称为 PIMPL(Pointer to IMPLementation) ,Opaque Pointer 等,是一种在类中只定义接口,而将私有数据成员封装在另一个实现类中的惯用法。该方法主要是为了隐藏类的数据以及减轻编译时的压力。

“柴郡猫”是什么鬼?就是下面这货:

柴郡猫(Cheshire cat)是英国作家刘易斯·卡罗尔(Lewis Carroll,1832-1898)创作的童话《爱丽丝漫游奇境记(Alice’s Adventure in Wonderland)》中的虚构角色,形象是一只咧着嘴笑的猫,拥有能凭空出现或消失的能力,甚至在它消失以后,它的笑容还挂在半空中。 – 来自百度百科

柴郡猫的能力和 PIMPL 的功能相一致,即虽然数据成员“消失”了(被隐藏了),但是我们的“柴郡猫”的笑容还是可以发挥威力。

下面通过例子来介绍一下 PIMPL 。

1 数据隐藏

C++ 中我们在头文件中定义类,比如一个简单的 Student 类由如下方式定义:

// student.hclass Student{public:Student(); // Constructor~Student(); // Destructorvoid sayHello();std::string getName() const;void setName(std::string name);int getAge() const;void setAge(int age);private:string _name;unsigned int _age;};

这里 _name 和 _age 是 Student 类的私有数据成员。然而使用该类的客户往往更关心类的接口(该类能提供哪些服务),我们希望隐藏 Student 类的私有数据成员,这时候就可以利用 PIMPL 模式:定义一个实现类,将 Student 类的数据封装到这个实现类中,同时在 Student 类中保留一个指向该实现类的指针变量。用代码解释更清楚:

// student.hclass Student{public:Student(); // Constructor~Student(); // Destructorvoid sayHello();std::string getName() const;void setName(std::string name);int getAge() const;void setAge(int age);private:class CheshireCat; // Forward declarationCheshireCat *_smileCat;};;class Student::CheshireCat{public:CheshireCat() :_name(string(“Guy”)), _age(18) {}~CheshireCat() {}string _name;int _age;};Student::Student() :_smileCat(new CheshireCat()){}Student::~Student(){delete _smileCat;}void Student::sayHello(){cout << “Hello! My name is ” <<_smileCat->_name << “.” << endl;cout << “I am ” << _smileCat->_age <<” years old.” << endl;}string Student::getName(){return _smileCat->_name;}void Student::setName(string name){_smileCat->_name = name;}int Student::getAge(){return _smileCat->_age;}void Student::setAge(int age){_smileCat->_age = age;}

好了,现在Student类的接口没有任何变化,但是头文件中原有的私有数据成员消失了,,只留下一只微笑的柴郡猫(CheshireCat *_smileCat;)。

2 节省编译时间

使用 PIMPL 可以帮助我们节省程序编译的时间。考虑下面这个类:

A{//…private:BigClass big;VeryBigClass veryBig;};

我们知道C++中有头文件(.h)和实现文件(.cpp),一旦头文件发生变化,不管多小的变化,所有引用它的文件都必须重新编译。对于一个很大的项目,C++一次编译可能就会耗费大量的时间,如果代码需要频繁改动,那真的是不能忍。这里如果我们把 BigClass big; 和 VeryBigClass veryBig; 利用 PIMPL 封装到一个实现类中,就可以减少 A.h 的编译依赖,起到减少编译时间的效果:

// A.hclass A {public:// 与原来相同的接口private:struct AImp;AImp *pimpl;};

3 副作用

使用 PIMPL 需要在堆空间上分配和释放内存,内存开销增加,同时也需要更多的间接指针跳转,因此有一些副作用。

虽然如此,PIMPL 仍然是一种实现数据隐藏、减少编译时间的有效方法。除非会引起显著的程序性能下降,推荐使用 PIMPL 进行设计。

参考

多看书,看好书。

C++中的PIMPL设计模式

相关文章:

你感兴趣的文章:

标签云: