🐭 pImpl 惯用法
pImpl 惯用法不是啥新东西,主要用来解决下面几个问题:
- 保持 ABI (二进制接口) 兼容性
- 减少依赖,缩短编译时间
- 接口实现分离,隐藏具体实现
🐂 使用独占指针实现 pImpl 惯用法
对于 pImpl 惯用法来说,最适合使用独占指针来实现,由于默认的析构函数不能作用于不完整类型,需要定制,进而需要定制移动操作,拷贝操作可有可无。
以一个画图类的设计来举例说明:
接口:** ```cpp // Graphics.hpragma once
include
class Graphics { public: Graphics(); // outline ctor ~Graphics(); // outline dtor Graphics(const Graphics &rhs); // outline copy ctor Graphics &operator=(const Graphics &rhs); // outline copy assignment Graphics(Graphics &&rhs); // outline move ctor Graphics &operator=(Graphics &&rhs); // outline move assignment
public: void drawLine(int x0, int y0, int x1, int y1) const; void drawRectangle(int x0, int y0, int x1, int y1) const;
private:
class Impl; // forward declaration
std::unique_ptr
:::tips前向声明了一个不完整类型 'Impl',不完整类型支持非常有限的操作:<br />独占指针与共享指针对不完整类型的支持是不一样的:1. 共享指针与独占指针默认都使用 delete 操作符作为资源清理函数1. 资源清理函数是独占指针类型的一部分,而不是共享指针类型的一部分1. 编译器在生成默认析构函数的时候,对于独占指针需要知道完整的类型,对于共享指针则不需要1. 因此,默认生成的特殊成员函数没法工作,需要在类外定义实现,并且让编译器看到 'Impl' 的完整类型:::**<br />**实现:**```cpp// Graphics.cpp#include "Graphics.h"#include <iostream>#include <string>class Graphics::Impl {public:void drawLine(int x0, int y0, int x1, int y1) const {std::cout << "drawLine\n";};void drawRectangle(int x0, int y0, int x1, int y1) const {std::cout << "drawRectangle\n";};private:std::string version_{"1.0"};};// ctor and dtorGraphics::Graphics() : pImpl(std::make_unique<Impl>()) {}Graphics::~Graphics() = default;// copy operations, just use the Graphics::Impl object copy operationsGraphics::Graphics(const Graphics &rhs): pImpl(std::make_unique<Impl>(*(rhs.pImpl))){};Graphics &Graphics::operator=(const Graphics &rhs) {*pImpl = *(rhs.pImpl);return *this;}// move operations, just use the unique_ptr move operationsGraphics::Graphics(Graphics &&rhs) = default;Graphics &Graphics::operator=(Graphics &&rhs) = default;void Graphics::drawLine(int x0, int y0, int x1, int y1) const {pImpl->drawLine(x0, y0, x1, y1);}void Graphics::drawRectangle(int x0, int y0, int x1, int y1) const {pImpl->drawRectangle(x0, y0, x1, y1);}
:::tips
在类外对特殊成员函数的实现,我们需要让编译器看到 ‘Impl’ 的完整类型
如果选择 ‘Impl’ 的类型为共享指针,则不需要专门在类外定义 ‘= default’ 的特殊成员函数
:::
客户端:**
// client.cpp#include "Graphics.h"int main() {// basic usageGraphics g;g.drawLine(0, 0, 1, 1); // drawLineg.drawRectangle(0, 0, 1, 1); // drawRectangle// move operationsauto g0(std::move(g));g0.drawLine(2, 2, 3, 3); // drawLine// copy operationsauto g1 = g0;g1.drawRectangle(4, 4, 5, 5); // drawRectanglereturn 0;}
🐯 总结
- pImpl 主要是为了减少依赖,缩短编译时间服务的
- 注意独占指针的前向声明问题,不完整类型析构问题
- 指针的选用优先级:独占指针 > 原始指针 > 共享指针 > 弱共享指针
