1. 為什麼使用inline
在大多數機器上,調用函數都要做很多工作:調用前要先儲存寄存器,並在返回時恢複,複製實參,程式還必須轉向一個新位置執行.
使用內嵌函式可以避免函數調用的開銷.
內聯說明對於編譯器來說只是一個建議,編譯器可以選擇忽略這個建議.
2.內嵌函式定義
內嵌函式的定義對編譯器而言必須是可見的,以便編譯器能夠在調用點內聯展開該函數的代碼.此時,僅有函數原型是不夠的.
內嵌函式可能要在程式中定義不止一次,只要內嵌函式的定義在某個源檔案中只出現一次,而且在所有源檔案中,其定義必須是完全相同的.把內嵌函式的定義放在標頭檔中,可以確保在調用函數時所使用的定義時相同的,並且保證在調用點該函數的定義對編譯器可見.
內嵌函式的應該在標頭檔中定義(建議).
3. 類中的內嵌函式
在類內部定義的成員函數,將自動作為inline處理.
可以在類定義體內部制定一個成員為inline,作為其聲明的一部分.或者,也可以在類定義體外部的函數定義上指定inline.在聲明和定義處指定inline都是合法的.
不在類定義體內定義的inline成員函數,其定義通常放在有類定義的同一個標頭檔中.
class Screen{public: typedef std::string::size_type index;// implicitly inline where defined inside the class declarationchar get() const {return contents[curosr];}// explicitly declared as inline, willl be defined outside the class declarationinline char get(index ht, index wd) const;// inline not specified in class declaration, but can be defined inline laterindex get_curosr() const;};// inline declared in the class declaration; no need to repeat on the definitionchar Screen::get(index r, index c) cosnt{ index row = r* width;return contents[row + c];}// not declared as inline in the class declaration, but ok to make inline in definitioninline Screen::index Screen:get_cirsot() const{ return cursor;}
參考:Effective C++, 條款30: 透徹瞭解inlining的裡裡外外