PIMPL means pointer to implementation, or private implementation. It shows up a lot in C++ projects and libraries. The basic idea is simple: keep private data and methods out of the public interface. Put the class implementation details behind a separate pointer-owned class. This is useful when building a stable ABI for a C++ library interface, and for cutting down compile-time dependencies.
Implementation
Modern C++ doesn’t really want owning raw pointers. A smart pointer is enough for PIMPL.
#include <iostream>
#include <memory>
class AppPrivate
{
public:
AppPrivate() {}
void print(std::string info) {
std::cout << info << std::endl;
}
};
class Application
{
public:
Application(): d_ptr(new AppPrivate) {
}
void call_print(std::string info) {
d_ptr->print(info);
}
private:
std::unique_ptr<AppPrivate> d_ptr;
};
int main(int argc, char *argv[])
{
Application a;
a.call_print("hello world");
return 0;
}
Last
C++ has header files(.h) and source files(.cpp). Once a header changes, even a tiny change, every file that includes it has to be compiled again. In a big project that can eat a lot of time. With PIMPL, the implementation is wrapped in a private class, so compile dependencies are smaller and compile time goes down.
d-pointer is one kind of opaque pointer implementation. The d-pointer is a private data member of the class. One nice part is faster builds, because the header changes less often. d-pointer is used a lot in Qt and KDE libraries.