constexpr try-catch
什么是 constexpr try-catch
C++20 允许在 constexpr 函数中使用 try-catch 块。在此之前,constexpr 函数中不能出现任何 try-catch 语句,即使 catch 分支在编译期永远不会被执行也不行。
需要明确的是,C++20 只是允许 try-catch 块出现在 constexpr 函数中,但 throw 表达式在编译期被执行时仍然会导致编译错误(即该调用不是常量表达式)。throw 在 constexpr 函数中的作用类似于编译期断言——如果执行到了 throw,说明参数不合法,编译器会报错。
C++26 的提案(P3068)进一步放宽了这个限制,允许在编译期真正地抛出和捕获异常,但这在 C++20/23 中还不支持。
演进过程
| 标准版本 | try-catch 在 constexpr 函数中的状态 |
|---|---|
| C++11/14/17 | 完全禁止——constexpr 函数中不能有 try-catch |
| C++20 | 允许 try-catch 块出现,但 throw 执行时仍是编译错误 |
| C++26(提案中) | 允许编译期真正抛出和捕获异常 |
为什么需要这个特性
这个特性主要是为了让标准库容器(如 std::vector)能标记为 constexpr。标准库的很多实现中使用了 try-catch 来提供强异常安全保证。比如 vector::insert() 在搬移元素时需要 try-catch 来保证:如果搬移过程中抛出异常,容器状态不会被破坏。
如果不允许 constexpr 函数中有 try-catch,这些标准库函数就不能标记为 constexpr,进而 constexpr std::vector 就无法实现。
基本示例
#include <iostream>
#include <stdexcept>
#include <vector>
#include <string>
#include <array>
#include <numeric>
// ============================
// 示例1:constexpr 函数中的 try-catch 块
// ============================
// C++20:try-catch 可以出现在 constexpr 函数中
constexpr int safe_access(const int* arr, int size, int index) {
try {
// 正常的数组访问逻辑
if (index < 0 || index >= size) {
throw "索引越界"; // 编译期执行到这里 → 编译错误
}
return arr[index];
} catch (...) {
// catch 块在编译期不会被执行
// 但代码的存在是合法的
return -1;
}
}
void basic_demo() {
constexpr int data[] = {10, 20, 30, 40, 50};
// 正常访问——不会触发 throw,编译期求值成功
constexpr int val = safe_access(data, 5, 2);
static_assert(val == 30);
std::cout << "data[2] = " << val << std::endl;
// 越界访问——触发 throw,编译期求值失败(编译错误)
// constexpr int bad = safe_access(data, 5, 10); // 编译错误!
// 运行期调用——throw 正常抛出异常,catch 正常捕获
int runtime_index = 10;
int runtime_val = safe_access(data, 5, runtime_index);
std::cout << "运行期越界访问结果: " << runtime_val << std::endl; // -1
}
// ============================
// 示例2:throw 作为编译期断言
// ============================
constexpr int factorial(int n) {
if (n < 0) {
throw "阶乘不接受负数"; // 编译期参数验证
}
if (n > 20) {
throw "数值太大,会溢出"; // 编译期溢出保护
}
int result = 1;
for (int i = 2; i <= n; ++i) {
result *= i;
}
return result;
}
void assertion_demo() {
// 合法参数——编译期求值成功
constexpr int f5 = factorial(5);
static_assert(f5 == 120);
std::cout << "5! = " << f5 << std::endl;
constexpr int f10 = factorial(10);
static_assert(f10 == 3628800);
std::cout << "10! = " << f10 << std::endl;
// 非法参数——编译错误
// constexpr int bad1 = factorial(-1); // 编译错误:阶乘不接受负数
// constexpr int bad2 = factorial(21); // 编译错误:数值太大
// 运行期调用——throw 正常工作
try {
int result = factorial(-1);
std::cout << result << std::endl;
} catch (const char* msg) {
std::cout << "运行期异常: " << msg << std::endl;
}
}
// ============================
// 示例3:constexpr vector 的基础——try-catch 使能
// ============================
// std::vector 能在 constexpr 中使用,
// 正是因为 C++20 允许其内部实现使用 try-catch
constexpr int vector_computation() {
std::vector<int> v;
// push_back 的内部实现可能用了 try-catch
// 来保证强异常安全
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
v.push_back(5);
// 在编译期使用标准算法
int sum = std::accumulate(v.begin(), v.end(), 0);
return sum;
// vector 析构——内存释放(瞬态分配)
}
void vector_demo() {
constexpr int result = vector_computation();
static_assert(result == 15);
std::cout << "vector 求和: " << result << std::endl;
}
// ============================
// 示例4:带异常安全保证的 constexpr 函数
// ============================
// 模拟一个需要异常安全的操作
template<typename T>
constexpr void swap_with_safety(T& a, T& b) {
// try-catch 确保即使某一步失败,状态也不会损坏
T temp = a;
try {
a = b;
b = temp;
} catch (...) {
// 恢复原始状态
a = temp;
// 在编译期,catch 块不会被执行
// 但在运行期,它提供异常安全保证
}
}
constexpr int swap_test() {
int x = 10, y = 20;
swap_with_safety(x, y);
return x * 100 + y; // 2010
}
void safety_demo() {
constexpr int result = swap_test();
static_assert(result == 2010);
std::cout << "交换后: x=" << result / 100 << ", y=" << result % 100 << std::endl;
}
// ============================
// 示例5:编译期验证 + 运行期错误处理
// ============================
constexpr double safe_sqrt(double x) {
if (x < 0.0) {
throw "不能对负数求平方根";
}
// 牛顿迭代法
if (x == 0.0) return 0.0;
double guess = x / 2.0;
for (int i = 0; i < 100; ++i) {
guess = (guess + x / guess) / 2.0;
}
return guess;
}
constexpr double safe_divide(double a, double b) {
if (b == 0.0) {
throw "除数不能为零";
}
return a / b;
}
// 组合多个可能失败的编译期操作
constexpr double compute_hypotenuse(double a, double b) {
// 编译期:如果参数非法,throw 触发编译错误
// 运行期:throw 正常抛出异常
double sum = a * a + b * b;
return safe_sqrt(sum);
}
void combined_demo() {
constexpr double h = compute_hypotenuse(3.0, 4.0);
// 5.0(勾股定理)
std::cout << "斜边长: " << h << std::endl;
constexpr double d = safe_divide(100.0, 4.0);
static_assert(d == 25.0);
std::cout << "100 / 4 = " << d << std::endl;
// 编译错误示例:
// constexpr double bad_sqrt = safe_sqrt(-1.0); // 编译错误
// constexpr double bad_div = safe_divide(1.0, 0.0); // 编译错误
}
int main() {
std::cout << "=== 基本用法 ===" << std::endl;
basic_demo();
std::cout << "\n=== 编译期断言 ===" << std::endl;
assertion_demo();
std::cout << "\n=== constexpr vector ===" << std::endl;
vector_demo();
std::cout << "\n=== 异常安全 ===" << std::endl;
safety_demo();
std::cout << "\n=== 组合验证 ===" << std::endl;
combined_demo();
return 0;
}throw 在 constexpr 中的双重角色
throw 在 constexpr 函数中有两种行为,取决于调用上下文:
| 调用上下文 | throw 的行为 |
|---|---|
| 编译期(constexpr 变量初始化、static_assert 等) | 导致该表达式不是常量表达式 → 编译错误 |
| 运行期(普通变量初始化、非 constexpr 上下文) | 正常抛出异常,可以被 catch 捕获 |
这意味着同一个 constexpr 函数在编译期相当于有参数验证(throw = 编译错误),在运行期则是正常的异常处理。
constexpr int divide(int a, int b) {
if (b == 0) throw "除零"; // 编译期:编译错误;运行期:抛异常
return a / b;
}
// 编译期
constexpr int ok = divide(10, 2); // 正确:5
// constexpr int bad = divide(10, 0); // 编译错误
// 运行期
try {
int x = 0;
int result = divide(10, x); // 抛出异常
} catch (const char* msg) {
// 捕获异常
}适用场景
- 让标准库容器(vector、string 等)支持 constexpr
- 编译期参数验证(throw 作为编译期断言)
- 编写同时适用于编译期和运行期的函数(编译期报编译错误,运行期报异常)
- 需要异常安全保证的 constexpr 函数
常见问题
C++20 的 constexpr try-catch 能在编译期真正捕获异常吗?
不能。C++20 只是允许 try-catch 语法出现在 constexpr 函数中。编译期如果执行到 throw,整个表达式不是常量表达式,直接编译错误,不会进入 catch 块。C++26 的提案(P3068)正在推进允许编译期真正抛出和捕获异常。
为什么不直接用 if 判断代替 try-catch?
标准库的实现中,try-catch 用于提供强异常安全保证——比如 vector 扩容时,如果复制/移动元素失败,需要回滚到原始状态。这种模式用 if 判断很难实现,因为你不知道哪一步会失败。
constexpr 函数中 throw 后面可以跟任意类型吗?
在编译期,throw 的对象类型不重要(因为 throw 触发的是编译错误,不是真正的异常)。在运行期,throw 正常工作,可以抛出任意类型。
C++26 的编译期异常有什么新进展?
P3068 提案允许编译期 throw 的异常被同一常量表达式中的 catch 捕获(类似瞬态分配——异常必须在常量表达式内被捕获)。这将使 constexpr 代码中的错误处理更加灵活。
注意事项
- C++20 允许 try-catch 在 constexpr 函数中出现,但编译期 throw 仍是编译错误
- catch 块在编译期不会被执行
- throw 在 constexpr 函数中相当于编译期断言
- 同一函数在编译期和运行期行为不同(throw = 编译错误 vs 抛异常)
- 这个特性的主要受益者是标准库实现(vector、string 等的 constexpr 化)
- C++26 可能允许编译期真正的异常抛出和捕获
编译器支持情况
| 编译器 | constexpr try-catch(C++20) | 最低版本 |
|---|---|---|
| GCC | 支持 | 10.0 |
| Clang | 支持 | 8.0 |
| MSVC | 支持 | 19.25 (VS 2019 16.5) |
总结
C++20 允许 try-catch 块出现在 constexpr 函数中,解决了标准库容器(如 std::vector)无法标记为 constexpr 的问题。这个特性本身比较简单——它只是放宽了 constexpr 函数的语法限制,让 try-catch 不再是禁止出现的语法结构。编译期执行到 throw 仍然会导致编译错误(该表达式不是常量表达式),catch 块在编译期不会被执行。throw 在 constexpr 函数中扮演了编译期断言的角色:合法参数正常计算,非法参数触发编译错误。同一个函数在运行期调用时,throw 和 catch 按正常的异常处理流程工作。