今天在首頁看到的,感覺不錯,摘過來保存一下:
http://www.shnenglu.com/CornerZhang/archive/2009/04/13/79004.html內(nèi)容如下:
頭文件依賴,Pimpl法,加速編譯
舉個例子:
// File: SoundSystem.h
#include "StreamFilter.h"
#include "Emitters."
class SoundSystem {
public:
// ...
private:
StreamFilter currentFilter;
EmitModeConfig modeConfig;
};
一目了然的是,看得出SoundSystem實現(xiàn)使用了StreamFilter和EmitModeConfig的定義,所以#include 了他們的定義在此SoundSystem.h中,可是隨著項目的不斷推進,class SoundSystem中依賴的使用類型會增多,它的header被引入到其它模塊中,不知不覺的編譯時間越來越長,改進之:
// File: SoundSystem.h
class StreamFilter;
class EmitModeConfig;
class SoundSystem {
public:
// ...
private:
StreamFilter* currentFilterPtr;
EmitModeConfig* modeConfigPtr;
};
// File: SoundSystem.cpp
#include "StreamFilter.h"
#include "Emitters."
SoundSystem::SoundSystem() {
//...
currentFilterPtr = new StreamFilter;
modeConfigPtr = new EmitModeConfig;
}
SoundSystem::~SoundSystem() {
delete currentFilterPtr;
delete modeConfigPtr;
//...
}
這么一來,把StreamFilter和EmitModeConfig的#include藏到了SoundSystem的實現(xiàn)代碼中,以后對SoundSystem的部分改動不會導致其它模塊的rebuild哦,不過由此可能會犧牲一點效率吧!
記得,有位微軟的C++翹楚人物,Herb Sutter給這種技巧稱為Pimpl ( Private Implemention ), 用的恰到好處時,可以提高項目開發(fā)速度,同時模塊的頭文件間的#include關(guān)系得以緩解,可以避開循環(huán)依賴,而且可以獲得一個良好的物理設(shè)計。
總結(jié):
Pimpl方法感覺很不錯,
使用這個方法的時候,一定要注意的是在這個地方的變化,這個是我第二遍看的時候才注意到的.
class SoundSystem {
public:
// ...
private:
StreamFilter currentFilter;
EmitModeConfig modeConfig;
};
采用Pimpl方法后,變?yōu)?br> class SoundSystem {
public:
// ...
private:
StreamFilter* currentFilterPtr;
EmitModeConfig* modeConfigPtr;
};
所以在.cpp文件中就有了new和delete的操作.
對于這種方法有一個疑問?對于那種存在包含眾多類的情況下,這種方法的駕馭不是一般人能夠掌握的吧.或許這種方法就不太使用了,不如等待一會,編譯.
posted on 2009-04-16 10:11
Sandy 閱讀(2888)
評論(1) 編輯 收藏 引用 所屬分類:
C++