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

1 answer 1

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

For example, we create a library that itself depends on third-party libraries. In this case, we are going to transfer our library to someone else without source code. In order not to drag dependencies in the form of header files (at a minimum) and not to reveal too many implementation details in the class interface (as a maximum), 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 method is used to create C ++ library interfaces with a stable ABI and reduce dependencies at compile time.

Since the private members of the class data participate in the representation of the object, affecting the size and layout, and also because the private member functions of the class are involved in resolving the overload (which happens before checking access to membership), any change to these implementation details requires recompiling all users of the class .

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

useful links

    Protected by community spirit 1 Dec '18 at 17:29 .

    Thank you for your interest in this issue. Since he collected a large number of low-quality and spam responses, which had to be deleted, now it’s necessary to have 10 reputation points on the site (the bonus for account association is not counted ).

    Maybe you want to answer one of the unanswered questions ?