Modern (Effective) C++ - Pimpl Idiom - Unique pointer application Part 2

This article is inspired from Item 18 and 22 of Effective Modern C++ by Scott Meyers.

Pimpl idiom short for Pointer to implementation, is used for two main reasons
1. To reduce the compiler dependencies and hence resulting in shorter build times.
2. To hide our data structure.

In Pimpl, we move our data members of our class from our .h file to another implementation structure in our .cpp file. In the .h file we forward declare our implementation structure, and create a pointer to it. (We cannot create an object of type implementation only pointer, since we know the size of the pointer)

Here is an example to explain Pimpl,

The class Car without using Pimpl


Now suppose the Car.h is included in many of our project's code files, which doesn't really use std::map. But since we are including Car.h, we are going to include map.h anyway. This is going to add a lot of code bloat.
Hence to resolve this issue, we will now proceed move all the data members to a separate struct in the Car.cpp file and in the .h file, we will include the pointer to this created struct. We can also now move the include<map> to Car.cpp .

This will lead to improvement in our build time, since map is not included by default with Car.h. The improvement will depend on -
  • The number of files where Car.h included.
  • Size of map.h file.

More about what we can can and cannot do with forward declarations is explained in this link.

This is how Pimpl was being implemented in the older C++ versions, But since C++11, we are discouraged to use raw pointers. Instead we must use smart pointers wherever possible.

I will cover Pimpl idiom in modern C++, along with it's idiosyncrasies, in the next article


Modern (Effective) C++ - Pimpl Idiom - Unique pointer application Part 2   Modern (Effective) C++ - Pimpl Idiom - Unique pointer application Part 2 Reviewed by zeroingTheDot on February 07, 2018 Rating: 5

No comments:

Powered by Blogger.