Renan Greinert Renan Greinert - 1 month ago 7
C++ Question

Is the pImpl idiom really used in practice?

I am reading the book "Exceptional C++" by Herb Sutter, and in that book I have learned about the pImpl idiom. Basically, the idea is to create a structure for the

private
objects of a
class
and dynamically allocate them to decrease the compilation time (and also hide the private implementations in a better manner).

For example:

class X
{
private:
C c;
D d;
} ;


could be changed to:

class X
{
private:
struct XImpl;
XImpl* pImpl;
};


and, in the CPP, the definition:

struct X::XImpl
{
C c;
D d;
};


This seems pretty interesting, but I have never seen this kind of approach before, neither in the companies I have worked, nor in open source projects that I've seen the source code. So, I am wondering it this technique is really used in practice?

Should I use it everywhere, or with caution? And is this technique recommended to be used in embedded systems (where the performance is very important)?

Answer

So, I am wondering it this technique is really used in practice? Should I use it everywhere, or with caution?

Of course it is used, and in my project, in almost every class, for several reasons you mentioned :

  • data hiding
  • recompilation time is really decreased, since only the source file needs to be rebuilt, but not the header, and every file that includes it
  • binary compatibility. Since the class declaration doesn't change, it is safe to just update the library (assuming you are creating a library)

is this technique recommended to be used in embedded systems (where the performance is very important)?

That depends on how powerful your target is. However the only answer to this question is : measure and evaluate what you gain and lose.