Browse DevX
Sign up for e-mail newsletters from DevX


Use the Pimpl Idiom to Reduce Compilation Time and Enhance Encapsulation : Page 2

Changes in the implementation details of a single infrastructure class don't have to trigger a wholesale recompilation of the numerous classes referring to the modified class. Find out how applying the Pimpl idiom can help you reduce compilation time and enhance encapsulation.




Building the Right Environment to Support AI, Machine Learning and Deep Learning

Presenting the Problem
Suppose you are designing a custom string class that is used in a large-scale project. This means that dozens of other classes and modules will depend on the header file in which the string class is defined. Here's a slightly contrived implementation of this class for demonstration purposes:

//+++ file String.h #include <vector> #include <iostream> #include "Lock.h" class String { public: String(); ~String(); //..copy ctor et al. std::size_t length() const; std::ostream & operator << (std::ostream& s) const; //... private: std::vector <char> vc; std:size_t len; Lock lck; //multithreading support };

Each client that uses this class has to #include the header String.h. The problem is that whenever you change the private section of this class, every piece of code that uses this class has to be recompiled. Not only does this dependency increase compilation time considerably, it also compromises encapsulation.

Remove Redundant #includes
String.h #includes three other headers. The first two are known to take relatively long to compile because they are made up of several other internal headers and template code. Notice, however, that String.h contains only declarations of its member functions. Therefore, you don't really need the bulky <iostream> header to compile it. Replace it with the lightweight header <iosfwd>. Since String.h is #included in multiple source files, the overall effect can be noticeable.

Is it possible to remove <vector> and Lock.h as well? Yes, it is.

Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date