Code錛?/font>
1聽聽聽struct聽AImp;
2聽聽聽class聽A聽{
3聽聽聽public:
4聽聽聽聽聽//聽Same聽public聽interface聽as聽A,聽but聽all聽delegated聽to聽concrete聽implementation.
5聽聽聽private:
6聽聽聽聽聽AImp聽*聽pimpl;
7聽聽聽};
8聽
If you use a SmartPointer
and you only have one implementation, there is no need to make any of
the member functions virtual, except possibly the destructor. The
run-time cost of non-virtual member function calls is much lower, and a
compiler that does whole-program optimization can inline them even
though they're in a separate translation unit. Here's an example:
聽1聽聽//聽foo.h
聽2聽
聽3聽聽聽class聽foo_impl;
聽4聽
聽5聽聽聽class聽foo聽{
聽6聽聽聽聽聽//聽Boilerplate
聽7聽聽聽聽聽friend聽class聽foo_impl;
聽8聽聽聽聽聽foo()聽{}聽//聽so聽only聽foo_impl聽can聽derive聽from聽foo
聽9聽聽聽聽聽const聽foo_impl聽*聽impl()聽const;
10聽聽聽聽聽foo_impl聽*聽impl();
11聽聽聽public:
12聽聽聽聽聽virtual聽~foo()聽{}
13聽聽聽聽聽//聽Factories
14聽聽聽聽聽static聽std::auto_ptr<foo>聽create(int聽value);
15聽聽聽聽聽//聽Interface
16聽聽聽聽聽int聽value()聽const;
17聽聽聽};
18聽
19聽聽聽//聽foo.cpp
20聽
21聽聽聽class聽foo_impl聽:聽public聽foo聽{
22聽聽聽聽聽friend聽class聽foo;
23聽聽聽聽聽//聽Constructors聽mirroring聽the聽factory聽functions聽in聽foo
24聽聽聽聽聽explicit聽foo_impl(int聽value)聽:聽value_(value)聽{}
25聽聽聽聽聽//聽Member聽data
26聽聽聽聽聽int聽value_;
27聽聽聽};
28聽
29聽聽聽inline聽const聽foo_impl聽*聽foo::impl()聽const聽{
30聽聽聽聽聽return聽static_cast<const聽foo_impl聽*>(this);
31聽聽聽}
32聽聽聽inline聽foo_impl聽*聽foo::impl()聽{
33聽聽聽聽聽return聽static_cast<foo_impl聽*>(this);
34聽聽聽}
35聽
36聽聽聽std::auto_ptr<foo>聽foo::create(int聽value)聽{
37聽聽聽聽聽return聽std::auto_ptr<foo>(new聽foo_impl(value));
38聽聽聽}
39聽
40聽聽聽int聽foo::value()聽const聽{聽return聽impl()->value_;聽}
41聽
42聽
Here, the destructor needs to be declared virtual foo so that
std::auto_ptr<foo> calls foo_impl's destructor. If you use
boost::shared_ptr<foo> instead, even that doesn't need to be
virtual, because shared_ptr remembers how to call the correct
destructor. (This doesn't improve performance or memory use, because
shared_ptr is larger and slower than auto_ptr, but if you need to use
shared_ptr anyway you may as well eliminate the virtual destructor.) -- BenHutchings
鍙傝冮槄璇伙細
Effective C++
http://c2.com/cgi/wiki?PimplIdiom
http://en.wikipedia.org/wiki/Opaque_pointer

]]>