O'Reilly logo

Exceptional C++: 47 Engineering Puzzles, Programming Problems, and Solutions by Herb Sutter

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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" ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required