Pimpl For Compile-Time Encapsulation (Modern C++)


The new home for Visual Studio documentation is Visual Studio 2017 Documentation on docs.microsoft.com.

The pimpl idiom is a modern C++ technique to hide implementation, to minimize coupling, and to separate interfaces. Pimpl is short for "pointer to implementation." You may already be familiar with the concept but know it by other names like Cheshire Cat or Compiler Firewall idiom.

Here's how the pimpl idiom can improve the software development lifecycle:

  • Minimization of compilation dependencies.

  • Separation of interface and implementation.

  • Portability.

// my_class.h  
class my_class {  
   //  ... all public and protected stuff goes here ...  
   class impl; unique_ptr<impl> pimpl; // opaque type here  

The pimpl idiom avoids rebuild cascades and brittle object layouts. It's well suited for (transitively) popular types.

Define the impl class in the .cpp file.

// my_class.cpp  
class my_class::impl {  // defined privately here  
  // ... all private data and functions: all of these  
  //     can now change without recompiling callers ...  
my_class::my_class(): pimpl( new impl )  
  // ... set impl values ...   

Consider whether to add support for non-throwing swap specialization.

Welcome Back to C++
C++ Language Reference
C++ Standard Library