Windows apps
Collapse the table of content
Expand the table of content
Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

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

 

For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.

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 ...  
private:  
   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

Show:
© 2016 Microsoft