首頁 > 軟體

C++行內函式

2021-01-16 16:00:21

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++官方
以上個人理解內容如有錯誤,還請指點糾正


IT145.com E-mail:sddin#qq.com