std::unreachable
来自 cppreference.cn
定义于头文件 <utility> |
||
[[noreturn]] void unreachable(); |
(since C++23) | |
在给定点调用未定义行为。
实现可以使用它来优化不可能的代码分支(通常在优化构建中),或者捕获它们以防止进一步执行(通常在调试构建中)。
目录 |
[编辑] 注释
特性测试 宏 | 值 | Std | 特性 |
---|---|---|---|
__cpp_lib_unreachable |
202202L |
(C++23) | std::unreachable
|
[编辑] 可能的实现
[[noreturn]] inline void unreachable() { // Uses compiler specific extensions if possible. // Even if no extension is used, undefined behavior is still raised by // an empty function body and the noreturn attribute. #if defined(_MSC_VER) && !defined(__clang__) // MSVC __assume(false); #else // GCC, Clang __builtin_unreachable(); #endif } |
[编辑] 示例
运行此代码
#include <cassert> #include <cstddef> #include <cstdint> #include <utility> #include <vector> struct Color { std::uint8_t r, g, b, a; }; // Assume that only restricted set of texture caps is supported. void generate_texture(std::vector<Color>& tex, std::size_t xy) { switch (xy) { case 128: [[fallthrough]]; case 256: [[fallthrough]]; case 512: /* ... */ tex.clear(); tex.resize(xy * xy, Color{0, 0, 0, 0}); break; default: std::unreachable(); } } int main() { std::vector<Color> tex; generate_texture(tex, 128); // OK assert(tex.size() == 128 * 128); generate_texture(tex, 32); // Results in undefined behavior }
可能的输出
Segmentation fault
[编辑] 参见
[[assume(expression)]] (C++23) |
指定表达式在给定点将始终求值为 true (属性说明符) |
(C++20) |
告知编译器指针已对齐 (函数模板) |
C 文档 for unreachable
|
[编辑] 外部链接
1. | GCC 文档: __builtin_unreachable
|
2. | Clang 文档: __builtin_unreachable
|
3. | MSVC 文档: __assume
|