GotW #100 demonstrated the best way to express the Pimpl idiom using only standard C++11 features:
// in header file class widget { public: widget(); ~widget(); private: class impl; unique_ptr<impl> pimpl; }; // in implementation file class widget::impl { // ::: }; widget::widget() : pimpl{ new impl{ /*...*/ } } { } widget::~widget() { } // or =default
Guru Question
Is it possible to make the widget code easier to write by wrapping the Pimpl pattern in some sort of library helper? If so, how?
Try to make the widget code as convenient and concise as possible to write, with any compiler-generated semantics either correct by default or producing compile-time errors if the widget author forgets to write them.
[Update: Removed move operations from the basic pattern. Since not all Pimpl’d types need to be move-aware, it’s not really part of the core pattern.]