C++內聯函數
- 2021 年 1 月 16 日
- 筆記
C++對代碼有許多優化的地方,從某種程度上來看,內聯函數就是一種優化,看一下C++官方標準對inline的描述:
When the compiler inline-expands a function call, the function』s code gets inserted into the caller』s code stream (conceptually similar to what happens with a #define macro). This can, depending on a zillion other things, improve performance, because the optimizer can procedurally integrate the called code — optimize the called code into the caller.
There are several ways to designate that a function is inline, some of which involve the inline keyword, others do not. No matter how you designate a function as inline, it is a request that the compiler is allowed to ignore: the compiler might inline-expand some, all, or none of the places where you call a function designated as inline. (Don』t get discouraged if that seems hopelessly vague. The flexibility of the above is actually a huge advantage: it lets the compiler treat large functions differently from small ones, plus it lets the compiler generate code that is easy to debug if you select the right compiler options.)
大致的意思就是:
當編譯器內聯擴展函數調用時,該函數的代碼將插入到調用者的代碼流中(概念上與#define宏類似)。 取決於不計其數的其他方面,這可以提高性能,因為優化器可以在過程上集成被調用的代碼—將被調用的代碼優化到調用程序中。
有幾種方法可以指定一個函數為內聯,其中一些涉及inline關鍵字,而其他則不涉及。 無論您如何將函數指定為內聯函數,都要求編譯器忽略該請求:編譯器可能會內聯擴展您調用被指定為內聯函數的位置的部分,全部或全部。 (不要灰心,因為這似乎望塵莫及。上面的靈活性實際上是一個巨大的優勢:它可以使編譯器將大型函數與小型函數區別對待,另外,如果選擇了,編譯器可以生成易於調試的代碼。 正確的編譯器選項。)
通俗的來講就是將函數的調用直接轉為編程語句來執行,從而減少棧的操作。
來看下面的代碼:
inline int function(int a ,int b ){
return a + b;
}
int main(){
cout<<function(10,20)<<endl;
}
該程序執行時直接通過優化可近似看做:
inline int function(int a ,int b ){
return a + b;
}
int main(){
cout<<10 + 20<<endl;
}
內聯函數會提高性能嗎?
沒有簡單的答案。內聯函數可能會使代碼變快,但可能會使代碼變慢。它們可能使可執行文件變大,可能使可執行文件變小。它們可能會引起顛簸,它們可能會阻止顛簸。它們可能而且通常與速度完全無關。
原文摘自C++官方
以上個人理解內容如有錯誤,還請指點糾正