码迷,mamicode.com
首页 > 编程语言 > 详细

C++: The PIMPL idiom

时间:2016-04-03 23:28:29      阅读:252      评论:0      收藏:0      [点我收藏+]

标签:

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

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

    https://msdn.microsoft.com/en-us/library/hh438477.aspx 

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

 

为什么需要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 };

 

C++: The PIMPL idiom

标签:

原文地址:http://www.cnblogs.com/blog-of-walker/p/5350888.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!