C++ pimpl

so so at so.so
Sun Feb 19 10:12:12 PST 2012


On Sunday, 19 February 2012 at 17:25:51 UTC, Robert Caravani 
wrote:
> On Friday 10 February 2012 20:23:59 so wrote:
>> I think i finally got a solution.
>> (Sorry for C++ code)
> Never mind, it is my mother tongue.
>> 
>> --- pimpl.hpp
>> template<typename T>
>> struct pimpl : noncopyable
>> {
>>   virtual ~pimpl() {}
>> };
>> 
>> --- lib.hpp
>> struct lib : public pimpl<lib>
>> {
>>   void fun(...);
>>   ...
>>   static lib* make();
>> };
>> 
>> --- lib.cpp
>> struct lib_impl : lib
>> {
>>   ... // data
>> };
>> 
>> void lib::fun(...)
>> {
>>   auto& r = *static_cast<lib_impl*>(this);
>>   ...
>> }
>> 
>> lib* lib::make()
>> {
>>   return new lib_impl;
>> }
>
> Well it is not bad, but how do you support derived classes with 
> this scheme? Derived classes would have to derive from the 
> implementation, so it would have to be public and compiled code 
> using the derived class would break on changes of the private 
> fields. Am I misinterpreting something?

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:

#define PIMPL(x) \
	private: \
		x(const x&); \
		const x& operator=(const x&); \
	protected: \
		x() {} \
	public: \
		virtual	~x() {}

now we can just use:

struct lib
{
    PIMPL(lib)
    ...
    ...
};

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.


More information about the Digitalmars-d mailing list