【C++基礎】inline函數__Jquery

來源:互聯網
上載者:User
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的裡裡外外


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.