Problem with private
|
|
Problems:
private
stuff included in header, breaking encapsulation- Undesired disclosure for proprietary projects
- Additional headers needed by
private
stuff, are included in header- Some 3rd-party headers do funky things
- Increased compilation time
- Breaks ABI, since whenever
private
changes, the class ABI might change as well
Using functions
C allows true encapsulation via opaque struct pointers. But what if I still want to use classes?
Enter PIMPL
Short for Pointer to Implementation
The header file would look like:
|
|
The actual implementation class MyClass::Impl
is only forward-declared in the header.
This requires us to forward-declare the destructor of MyClass
, otherwise the compiler generated definition will attempt to call the dtor of Impl
, which is not declared in this header.
The source file:
|
|
Always use unique_ptr
and std::make_unique
for PIMPL. DO NOT use a raw (or even void*
) pointer!
Copyable PIMPL class
PIMPL classes are already move-able for free, because the unique_ptr
is move-able.
To copy the actual Impl
object, the new MyClass
object should copy-construct its pimpl
member, provided the Impl
class is itself copyable.
|
|