内联函数与 constexpr
inline 优化、constexpr 编译期计算、static_assert
内联函数与 constexpr
inline 把函数体直接嵌入调用处,省去函数调用的开销。constexpr 更进一步——让函数在编译期执行。
学完本章你将: 掌握 inline 优化、constexpr 编译期计算。
inline —— 省去函数调用开销
cpp
#include <iostream>
// 短小、频繁调用的函数适合 inline
inline int max(int a, int b) {
return a > b ? a : b;
}
int main() {
int m = max(3, 5);
// 编译器可能展开为:int m = 3 > 5 ? 3 : 5;
std::cout << m << "\n";
return 0;
}
💡 inline 是建议而非命令——编译器有自己的判断。现代编译器会自动内联简单函数。
constexpr —— 编译期计算
cpp
// constexpr 函数:编译期可求值
constexpr int factorial(int n) {
return n <= 1 ? 1 : n * factorial(n - 1);
}
int main() {
// 编译期常量
constexpr int fact5 = factorial(5); // 编译期算出 120
int arr[fact5]; // 合法的数组大小!
// 也能在运行期调用
int n;
std::cin >> n;
std::cout << factorial(n) << "\n"; // 运行期调用
return 0;
}
constexpr 变量
cpp
constexpr int SIZE = 100; // 编译期常量
constexpr double PI = 3.1415926535;
// 用 constexpr 函数初始化
constexpr int ARR_SIZE = factorial(5); // 120
// 对比
const int c = readFromFile(); // OK——运行期赋值
// constexpr int ce = readFromFile(); // ❌ 编译期必须已知