Pointer to Implementation
lastmod 2018-08-17created 2015-09-241 edits
The Pimpl (Pointer to Implementation) Idiom is a technique that replaces member variables of user-defined types that require an include with a pointer to a struct containing those member variables.
Synopsis
//in header Widget.h
#include <string>
#include <vector>
#include <Gadget.h>
class Widget{
public:
Widget();
...
private:
std::string name;
std::vector<double> data;
Gadget g1, g2, g3;
}
Without the Pimpl Idiom, this is the kind of header file you commonly see. The problem with a header file like this is that it includes other header files. When you use #include, the preprocessor copies the contents of that header in verbatim. (Assuming no optimization.) Then every cpp file that includes Widget.h also gets every header that Widget.h includes, so the amount of code becomes very large. Therefore, the more headers a header includes, the longer the compile time.
Another problem is re-complie. Standard library functions like string or vector rarely change, but headers for user-defined classes like Gadget are likely to change often. If Gadget changes, every other file that includes Widget.h has no choice but to be recompiled as well. Because of these problems, it is best for headers to avoid including other headers whenever possible. That is why the Pimpl Idiom is used.
Pimpl Idiom in C++ 98
//in header Widget.h
class Widget{
public:
Widget();
~Widget();
...
private:
struct Impl; //Impl구조체 선언
Impl* pImpl; //다른 멤버들이 들어갈 구조체의 포인터
}
Favorite site
References
-
Modern_Effecitve_Cpp_item_22_-_Pimple_Idiom.pdf ↩