C++ pimpl

Robert Klotzner jfanatiker at gmx.at
Sun Feb 26 13:03:35 PST 2012


> Whole purpose of this is hiding implementation from user with 
> "zero" cost.
> Derived classes has no places here. Using anything about derived 
> classes means "zero" cost is not your first concern. So just use 
> pure classes / interfaces, they are much cleaner and to the point.
> 
> > What's the purpose of the pimpl template?
> 
> template<typename T>
> struct pimpl : noncopyable
> {
>    virtual ~pimpl() {}
> };
> 
> "virtual ~pimpl() {}"
> 
> This is to get rid of leaking, you know we need to provide a 
> "virtual destructor" for an interface otherwise a base class has 
> no way of knowing it is a "base" class and when you delete a 
> pointer you would free only the memory base class allocated. But 
> i guess you are asking why it should be like this, another way is:

Yeah, I got that. What I don't get is why it needs to be a template?
Wouldn't a simple base class with a destructor suffice?

> I don't understand why this didn't get much attention either, i 
> am now using it in my framework and it rocks!
> 
> > What do you think about my proposal? Is it sane and feasible at 
> > all?
> 
> I am having trouble understanding the need for supporting class 
> hierarchies.
> Deriving from a private implementation feels quite wrong. A pimpl 
> IMO should be a black box.

Well my initial example was Qt. Take for example the QWidget class, you
usually derive from it in order to implement custom widgets and with the
PIMPL idiom it is ensured that your derived classes will not break upon
addition of private fields in QWidget. It is a black box, a derived
class does not have access to private fields.

The whole purpose of my proposal is, to really hide private fields so
that not just the API is stable, but also the ABI. 

Best regards,
Robert




More information about the Digitalmars-d mailing list