std::unreachable
什么是 std::unreachable
std::unreachable 是 C++23 引入的函数,定义在 <utility> 头文件中。它用于标记一个代码路径在运行时永远不会被执行到。调用 std::unreachable() 本身是未定义行为——它的存在是为了告诉编译器"这个地方不可能到达",让编译器据此做优化。
在 C++23 之前,GCC/Clang 用 __builtin_unreachable(),MSVC 用 __assume(false) 来表达同样的意思。std::unreachable 提供了标准化的跨平台方式。
#include <utility>
enum class Direction { North, South, East, West };
const char* to_string(Direction d) {
switch (d) {
case Direction::North: return "北";
case Direction::South: return "南";
case Direction::East: return "东";
case Direction::West: return "西";
}
std::unreachable(); // 告诉编译器:所有情况已覆盖,不会走到这里
}基本示例
#include <iostream>
#include <utility>
#include <string>
#include <cstdint>
#include <vector>
// ============================
// 示例1:switch 覆盖所有枚举值
// ============================
enum class Color { Red, Green, Blue };
const char* color_name(Color c) {
switch (c) {
case Color::Red: return "红色";
case Color::Green: return "绿色";
case Color::Blue: return "蓝色";
}
// 所有枚举值都已处理,不可能到达这里
// 没有 unreachable(),编译器可能警告"控制流到达非 void 函数末尾"
std::unreachable();
}
void switch_demo() {
std::cout << color_name(Color::Red) << std::endl;
std::cout << color_name(Color::Green) << std::endl;
std::cout << color_name(Color::Blue) << std::endl;
}
// ============================
// 示例2:default 分支
// ============================
enum class Weekday { Mon, Tue, Wed, Thu, Fri, Sat, Sun };
bool is_weekend(Weekday day) {
switch (day) {
case Weekday::Mon:
case Weekday::Tue:
case Weekday::Wed:
case Weekday::Thu:
case Weekday::Fri:
return false;
case Weekday::Sat:
case Weekday::Sun:
return true;
default:
std::unreachable(); // 不可能有其他值
}
}
void default_demo() {
std::cout << std::boolalpha;
std::cout << "周六是周末: " << is_weekend(Weekday::Sat) << std::endl;
std::cout << "周三是周末: " << is_weekend(Weekday::Wed) << std::endl;
}
// ============================
// 示例3:消除编译器警告
// ============================
// 没有 unreachable,编译器会警告"非所有路径都返回值"
int absolute_value(int x) {
if (x >= 0) return x;
if (x < 0) return -x;
std::unreachable(); // x 要么 >= 0 要么 < 0,不可能到这里
}
void warning_demo() {
std::cout << "|5| = " << absolute_value(5) << std::endl;
std::cout << "|-3| = " << absolute_value(-3) << std::endl;
}
// ============================
// 示例4:帮助编译器优化
// ============================
// 假设我们知道 value 一定在 1-4 范围内
int process(int value) {
switch (value) {
case 1: return 100;
case 2: return 200;
case 3: return 300;
case 4: return 400;
default:
// 编译器可以假设 value 只能是 1-4
// 因此可以消除范围检查,生成更优化的代码
std::unreachable();
}
}
void optimization_demo() {
// 只用有效值调用
for (int i = 1; i <= 4; i++) {
std::cout << "process(" << i << ") = " << process(i) << std::endl;
}
}
// ============================
// 示例5:与 assert 的区别
// ============================
void assert_vs_unreachable_demo() {
// assert:在 Debug 模式下检查条件,Release 下被移除
// 用途:验证不应该发生的条件
// assert(false); // Debug 下崩溃,Release 下什么都不做
// unreachable:告诉编译器这里不可达,用于优化
// 如果真的到达了,行为未定义(可能崩溃、可能继续执行垃圾代码)
// std::unreachable();
// 推荐组合使用:Debug 下 assert,Release 下 unreachable
// #ifdef NDEBUG
// std::unreachable();
// #else
// assert(false && "不应该到达这里");
// #endif
std::cout << "assert 用于调试检查,unreachable 用于优化提示" << std::endl;
}
// ============================
// 示例6:无限循环后
// ============================
[[noreturn]] void event_loop() {
while (true) {
// 处理事件...
// 这个函数永远不会返回
std::cout << "事件循环运行中(模拟一次后退出)" << std::endl;
return; // 仅用于演示
}
std::unreachable(); // 循环永远不会结束
}
// ============================
// 示例7:位运算中的不可能路径
// ============================
int count_leading_zeros_safe(std::uint32_t value) {
// 调用者保证 value != 0
if (value == 0) {
std::unreachable(); // 不可能是 0
}
int count = 0;
while ((value & 0x80000000u) == 0) {
count++;
value <<= 1;
}
return count;
}
void bitwise_demo() {
std::cout << "clz(1) = " << count_leading_zeros_safe(1) << std::endl;
std::cout << "clz(128) = " << count_leading_zeros_safe(128) << std::endl;
std::cout << "clz(0x80000000) = " << count_leading_zeros_safe(0x80000000u) << std::endl;
}
int main() {
std::cout << "=== switch 枚举 ===" << std::endl;
switch_demo();
std::cout << "\n=== default 分支 ===" << std::endl;
default_demo();
std::cout << "\n=== 消除警告 ===" << std::endl;
warning_demo();
std::cout << "\n=== 优化 ===" << std::endl;
optimization_demo();
std::cout << "\n=== assert vs unreachable ===" << std::endl;
assert_vs_unreachable_demo();
std::cout << "\n=== 位运算 ===" << std::endl;
bitwise_demo();
return 0;
}unreachable vs 其他方式
| 方式 | 标准 | 效果 | 可移植 |
|---|---|---|---|
std::unreachable() | C++23 | 未定义行为,编译器优化 | 是 |
__builtin_unreachable() | GCC/Clang | 同上 | 否 |
__assume(false) | MSVC | 同上 | 否 |
assert(false) | 所有版本 | Debug 崩溃,Release 无效果 | 是 |
std::abort() | 所有版本 | 程序终止 | 是 |
throw | 所有版本 | 抛出异常 | 是 |
适用场景
- switch 语句中已覆盖所有枚举值后的 default/末尾
- if-else 链中已覆盖所有逻辑分支后
- 消除"非所有路径都返回值"的编译器警告
- 帮助编译器对已知范围做优化
- 替代平台特定的
__builtin_unreachable()和__assume(false)
常见问题
如果代码真的执行到 unreachable 会怎样?
未定义行为。可能崩溃、可能执行垃圾指令、可能什么都不发生。在 Debug 构建中建议同时使用 assert。
unreachable 和 [[noreturn]] 有什么关系?
[[noreturn]] 标记函数永远不会返回(如 std::abort),std::unreachable 标记代码路径不会到达。unreachable 本身就是 [[noreturn]] 的。
应该在 Release 和 Debug 中都使用吗?
在 Release 中使用 unreachable 获得优化收益。在 Debug 中建议用 assert 来捕获 bug。一种常见做法是在 Debug 模式用 assert,Release 模式用 unreachable。
注意事项
- 调用 unreachable() 本身是未定义行为——只在确定不会到达时使用
- 不要用 unreachable 代替错误处理
- Debug 构建中建议配合 assert 使用
- 它是一个运行时构造,不是编译期检查
- 需要
<utility>头文件
总结
std::unreachable 是 C++23 提供的标准化工具,用于标记不可能到达的代码路径。它告诉编译器"这里不会执行到",让编译器据此优化(比如消除不必要的分支检查),同时消除"非所有路径返回值"之类的编译器警告。它替代了以前各编译器的非标准扩展(__builtin_unreachable 和 __assume(false))。使用时必须确保标记的路径确实不可达,否则是未定义行为。典型用法是在 switch 覆盖所有枚举值后使用,或在完整的 if-else 链之后使用。