Pimpl ẩn chi tiết cài đặt của class vào một private struct — trỏ bằng unique_ptr — chỉ khai báo forward declaration trong header.
cpp
// Widget.h — header thuần "interface"
class Widget {
public:
Widget();
~Widget();
void doWork();
private:
struct Impl; // forward declaration
std::unique_ptr<Impl> p_;
};
// Widget.cpp — chi tiết ẩn trong .cpp
struct Widget::Impl {
HeavyResource res; // type này không cần expose trong header
};
Widget::Widget() : p_(std::make_unique<Impl>()) {}
void Widget::doWork() { p_->res.process(); }Lợi ích:
- ABI stability: thay đổi Impl không cần recompile code dùng Widget.h.
- Compilation firewall: header nhẹ, không kéo vào các #include nặng.
- Encapsulation thực sự: private members trong header vẫn lộ tên kiểu — pimpl ẩn hoàn toàn.
Lưu ý: destructor phải được định nghĩa trong .cpp (nơi Impl complete) — không để compiler gen mặc định ở header.