On Tuesday, 22 October 2013 01:39:27 UTC+3, Rupert Swarbrick wrote:
> I'm coming back to writing some C++ after a few years in Lisp-land, and
> was wondering about the "pimpl idiom". I understand how to write and use
> it, and have done in the past. However, I don't really understand what
> it gains you over having an abstract base class in the header, along
> with a factory function.
We call it "pimpl" since we like Orcish language perhaps, rest call it
"Cheshire Cat", "Compiler firewall" or "Bridge pattern".
There is better separation of concerns. Abstraction implements external
interface. Implementor implements internal implementation.
There are more dynamics. For example when object behind pointer to
interface is made then it can not change its type anymore in C++.
The implementor that is behind abstraction of pimpl however may be
is dynamically replaced, shared, cached, reused or copied-on-write etc.
by abstraction. It is not business of user of abstraction but
externally it may feel like type has changed entirely during life-time
of abstraction.
Slight performance advantage of pimpl is that the virtual functions
are not needed. There may be virtual functions as implementor may be
polymorphic ... but those are not mandatory. So virtual functions
may be used when those improve performance, not when they describe
common interface.
> Presumably there's a significant difference, since people put up with
> the reams of boilerplate required for passing functions through to the
> implementation object. Can anyone explain to me what it is?
It is never clear if any of named advantages is substantial enough for
you.
> PS: I'm not sure whether there are strong feelings about whether to use
> this idiom or not. To be clear, I'm not trying to hear them! I can
> see obvious downsides to keeping a pointer to an implementation
> object (verbosity; have to be careful about destructor +
> exceptions...) and I'm interested to know what the upsides are.
I must say that pimpl has its downsides too. If the problem has simple
solution then it is easy to make it more complex by adding unneeded
pimpl. We should aim to keep things as simple as possible (just not
simpler than possible). So pimpl is good for complex enough objects.