inline 建議編譯器將函數呼叫處以函數本體直接展開,消除呼叫開銷 (參數壓棧、跳轉、返回)。類似宏展開,但具備型別安全、作用域、除錯支援。
inline int add(int a, int b) { return a + b; }
int main() {
int x = add(3, 5);
// 編譯器可能展開為:
// int x = 3 + 5;
}
| ✅ 適合 | ❌ 不適合 |
|---|---|
| 極短函數 (1-5 行) | 含迴圈/遞迴/複雜控制流 |
| 頻繁呼叫的熱點路徑 | 函數體大 (指令快取污染) |
| 存取器/判斷式/簡單運算 | 虛函數 (動態綁定無法內聯) |
| 模板/標頭檔實作 | 函數位址被取用 (&func) |
inline 只是建議,編譯器可忽略 (過大、遞迴、虛函數等)
// Math.h
inline int square(int x) { return x * x; }
// Math.cpp 不需要定義
constexpr int factorial(int n) {
return n <= 1 ? 1 : n * factorial(n - 1);
}
// 編譯期可計算,隱性 inline
__attribute__((always_inline)) void fast_path(); // 強制
__attribute__((noinline)) void cold_path(); // 禁止
gcc -O2 -finline-functions -Winline 顯示內聯決策警告objdump -d / gdb disassemble 檢查實際機器碼