C++: The PIMPL idiom

什么是PIMPL(pointer to implementation) ? see:

    http://stackoverflow.com/questions/8972588/is-the-pimpl-idiom-really-used-in-practice    

    http://www.cppsamples.com/common-tasks/pimpl.html

 其实PIMPL就是23种设计模式中bridge pattern的一种c++实现:

        https://en.wikipedia.org/wiki/Bridge_pattern

为什么需要PIMPL? Hurb Sutter:

Reason 1:

   1. If not used, compilation time would be long as you expected. For example:

1 // headerFile.h
2 class C{
3 //,,,
4 private:
5     AComplicatedType act_;
6 };

The header file containing class C's definition must also #include the header containing the definition for  AComplicatedType ,which in turn transitively includes every header that  AComplicatedType might need, and so on. If the headers are extensive, compilation times can be noticably affected.

Reason 2:

That is because C++ performs name lookup and then overload resolution before accessibility checking.

 1 //global function
 2 int Twice(int);               //1
 3 
 4 class Calc{
 5 public:
 6     string Twice(string);    //2
 7 
 8 private:
 9     char* Twice(char*);     //3
10 
11     int Test(){
12         return Twice(21);    //A: error. 2 or 3 would be unviable. Though 1 is viable,
13     }                        // it can't be considered because it's hidden
14 };
15 
16 Calc c;
17 c.Twice("Hello");            //B:error. 3 is inaccessible( 2 would work fine, but it can't be   
18                              //considered, because 3 is a better choice and  c++ perform overload 
19                              //resolution before accessibility checking

As illustrated in the comments above.

Reason 3:

Exeception guarantee. 

consider this:

1 class Widget{
2 public:
3     Widget& operator=(const Widget&);
4 
5 private:
6     T1 t1_;
7     T2 t2_;
8 };

what happen when  T1 and  T2 is constructing and an exception throwed up ?

This would be a better approach:

 1 class Widget{
 2 public:
 3     Widget& operator=(const Widget&);
 4 
 5 private:
 6     struct Impl;
 7     shared_ptr<Impl> pimpl_;
 8 };
 9 
10 Widget& Widget::operator=(const Widget&){
11     shared_ptr<Impl> temp( new Impl(/*...*/) );
12 
13 // change temp->t1_ to temp->t2_;
14 // if it fail, then throw, else commit using
15 
16     pimpl_ = temp;
17     return *this;
18 };

:)

原文地址:https://www.cnblogs.com/walkerlala/p/5350888.html