C/C++ Arena

Step 4 of 6

Pimpl

In a big codebase, changing a class's private members forces every file that includes its header to recompile, and in a shared library it breaks binary compatibility. The pimpl idiom ("pointer to implementation") hides the private data behind a pointer to a struct that's only declared in the header:

// widget.h
class Widget {
public:
    Widget();
    ~Widget();                       // declared here...
    int value() const;
private:
    struct Impl;                     // incomplete here
    std::unique_ptr<Impl> impl_;
};

// widget.cpp
struct Widget::Impl { int value = 42; std::vector<int> cache; };
Widget::Widget() : impl_(std::make_unique<Impl>()) {}
Widget::~Widget() = default;         // ...defined where Impl is complete

The destructor must be defined after Impl is complete, because unique_ptr needs to know how to delete it. Forgetting that is the classic pimpl compile error.

Your turn: the "header" part is written. Write the "source file" part: define Impl (holding a std::vector<std::string> of names), the constructor, destructor, move constructor, add and count.

Previous: Observers with weak_ptr Next: RAII wrappers for C libraries