C++: The PIMPL idiom

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C++: The PIMPL idiom相关的知识,希望对你有一定的参考价值。

什么是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的主要内容,如果未能解决你的问题,请参考以下文章

如何在 C++ 中获取抽象(?)pimpl 的调试信息?

C++在使用PImpl技术时,template/typename的不常见用法

何时在 C++ 中的嵌套类上使用 Pimpl 模式,反之亦然?

指向 C++ 中类的指针的 PIMPL 习语

使用 std::unique_ptr 的 C++ Pimpl Idiom 不完整类型

Qt 中的实现指针 (PIMPL)