PIMPL

Posted by shensunbo on March 27, 2026

PIMPL

PIMPL(Pointer to IMPLementation)是一种C++编程技术,用于隐藏类的实现细节,减少编译依赖,提高代码的封装性和可维护性。PIMPL通过将类的实现细节放在一个单独的实现类中,并在主类中使用一个指向该实现类的指针来访问这些细节。

when

  • 实现复杂、变动大的类;
  • 涉及第三方库封装不想暴露给调用者;
  • 需要考虑ABI兼容和编译加速场景;
  • 类的声明和实现想彻底分离,降低耦合。

典型场景

  • 涉及第三方库(如 OpenSSL、Qt)等实现成员不想暴露在头文件
  • 成员变量频繁变动,需要减少头文件因实现变化而引发的大规模重新编译
  • 需要对外部用户隐藏复杂实现,提高模块封装性
  • 提供二进制兼容(ABI兼容)库

demo

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// MyClass.h
class MyClass {
public:
    MyClass();
    ~MyClass();

    void doSomething();

private:
    class Impl;
    std::unique_ptr<Impl> pImpl;
};

// MyClass.cpp
class MyClass::Impl {
public:
    void doSomething() {
        // Implementation details
    }
};

MyClass::MyClass() : pImpl(std::make_unique<Impl>()) {}
MyClass::~MyClass() = default;
void MyClass::doSomething() { pImpl->doSomething(); }

// can also do definition here
void MyClass::Impl::doSomething() {
    // Implementation details
}