Chapter 30. The “Fast Pimpl” Idiom

Difficulty: 6

It's sometimes tempting to cut corners in the name of “reducing dependencies” or in the name of “efficiency,” but it may not always be a good idea. Here's an excellent idiom to accomplish both objectives simultaneously and safely.

Standard malloc and new calls are relatively expensive.[5] In the code below, the programmer originally has a data member of type X in class Y.

// Attempt #1 
//
// file y.h
#include "x.h"
class Y
{
  /*...*/
  X x_;
};

// file y.cpp
Y::Y() {}

This declaration of class Y requires the declaration of class X to be visible (from x.h). To avoid this, the programmer first tries to write:

 // Attempt #2 // // file y.h class X; class Y { /*...*/ X* px_; }; // file y.cpp #include "x.h" ...

Get Exceptional C++: 47 Engineering Puzzles, Programming Problems, and Solutions now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.