c++ – The pimpl c ++ technique

Question:

What is the pimpl technique and when should you use it?

Answer:

The idiom pimpl (pointer to implementation) is useful when we need to hide something. It provides an even deeper kind of encapsulation that masks not just the implementation, but also all of its dependencies.

For example, we are creating a library that itself depends on third party libraries. That being said, we're going to transfer our library to someone else without sources. In order not to pull dependencies in the form of header files (at least) and not reveal too many implementation details in the class interface (at most), we can use the pimpl idiom.

Example

// widget.h (interface)
class widget {
    // public members
private:
    struct impl;  // forward declaration of the implementation class
    // One implementation example: see below for other design options and trade-offs
    std::experimental::propagate_const< // const-forwarding pointer wrapper
        std::unique_ptr<                // unique-ownership opaque pointer
            impl>> pImpl;               // to the forward-declared implementation class
};

// widget.cpp (implementation)
struct widget::impl {
   // implementation details
};

This technique is used to create C ++ library interfaces with a stable ABI and reduce compile-time dependencies.

Because private data members of a class participate in the representation of an object, affecting size and layout, and because private member functions of a class are involved in overload resolution (which happens before membership access is checked), any change to these implementation details requires a recompilation of all users of the class. …

pImpl breaks this compilation dependency; implementation changes do not cause recompilation. Therefore, if a library uses pImpl in its ABI, newer versions of the library may change the implementation while remaining ABI-compatible with older versions.

useful links

Scroll to Top