So when trying to get in touch with the PIMPL idiom one finds two common ways of doing it:
Using forward declaration outside a class:
class PimplClass;
class VisibleClass
{
private:
PimplClass* d_ptr;
};
Using forward declaration inside a class:
// *.hpp
class VisibleClass
{
private:
struct PimplClass;
PimplClass* d_ptr;
};
// *.cpp file:
struct VisibleClass::PimplClass
{
int x;
};
Two questions here:
It's a forward-declaration too, but PimplClass is scoped inside VisibleClass.
That second solution has the advantage of not dumping an internal type into the global namespace. Keeping PimplClass scoped inside VisibleClass makes complete sense.
In both cases, the Pimpl idiom should generally use a std::unique_ptr to tie the lifetimes of the interface and the Impl together, rather than a raw owning pointer.
You may do a forward declaration within class scope. So the second example is absolutely correct.
The main plus of second example is that your PimplClass can't be accessed from anywhere but from VisibleClass because it is declared (forward-declared) inside it's private section.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With