C++2b(C++23)向けに提案されているコード不到達表明std::unreachable
関数の前提条件。
2022-02-09追記:2022年2月会合にて(PDF)P0627R6が採択され、C++2b標準<utility>ヘッダにstd::unreachable
関数が追加される。
2022-07-25追記:次世代C言語標準でもC2x(C23)向け提案(PDF)N2826が採択済み。<stddef.h>標準ヘッダの関数マクロ(function-like macro)unreachable()
として導入される。
「false
is true
」は常に成り立たない(恒偽命題)ため、unreachable
関数呼び出しは必ず未定義動作(undefined behavior)を引き起こす。つまり…どういうことだってばよ?
C++コンパイラは同関数呼び出しコード箇所には到達しないと仮定して最適化を行ってもよい、という規定となっている。提案文書(PDF) P0627R6 7. Proposed Wording より該当箇所を引用(下線部は強調)。
[[noreturn]] void unreachable();1 Preconditions:
false
istrue
. [ Note: This precondition cannot be satisfied, thus the behavior of callingunreachable
is undefined. -- end note]
2 [Example:int f(int x) { switch (x) { case 0: case 1: return x; default: std::unreachable(); } } int a = f(1); // OK; a has value 1 int b = f(3); // undefined behavior-- end example]
なお初期の提案文書では素直に自然言語で記述されていた。(PDF) P0627R3 7. Proposed Wordingより該当箇所を引用。
2 Effects: The behavior of calling
unreachable
is undefined.
関連URL