原文:
http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Forward_Declarations
可使用forward declaration來宣告classes,以避免不必要的#include。
(Note: 你可以forward declare一個class、function或template,但Google Style Guide只建議在必要時,使用forward declaration來宣告classes)
forward declaration的優點:
1. forward declaration可以減少不必要的#include,有些時候你只需要某header file中的一個symbol,但#include整個header file會引入很多你用不到的symbol,因而增加了compile的時間,也增加了.exe檔的size。
2. 當header file內容改變時,#include該header file的.cpp檔會需要被recompile,而增加了compile的時間。
forward declaration的缺點:
1. 你很難確定目前forward declaration的格式是否正確;因為軟體開發的期間會經過無數次的修改,有可能在header file中某個symbol的prototype已被修改,但你的forward declaration卻沒有跟著修改。
2. 你很難決定到底要使用forward declaration還是#include;在軟體開發的初期,也許forward declare少數幾個存在header file中的symbol就可以符合你的需求,但很有可能到了軟體開發的後期,你需要用到該header file中很多的symbol,此時#include整個header file是比較明智的選擇。
3. 從某個header file中forward declare多個symbols顯得很囉嗦,因為要打很多字。
4. 當你forward declare header file中的function或template,記得將來修改該function或template時,forward declaration的部分也要跟著修改。
5. forward declare std::中的symbols會造成undefined behavior。
6. 為了forward declaration而將object members改為pointer members會造成效能上的影響,也會使你的程式更為複雜。
7. forward declaration並不會帶來實際上效能的提升。
結論:
1. 當symbol為function或class template時,使用#include
2. 當symbol為一般的class時,可以使用forward declaration,但要小心以上提到的缺點,當你產生疑慮時,就使用#include
3. 不要為了想要減少#include的數量,就將原本的data members改為pointers
總是使用#include來引入你需要的symbols,不要相信forward declaration所帶來的symbol。