C++ 屬性:assume (C++23 起)
來自 cppreference.com
指定假定給定的表示式在給定點始終評估為 true,以允許編譯器根據給定的資訊進行最佳化。
目錄 |
[編輯] 語法
[[assume( 表示式 )]] |
|||||||||
表示式 | - | 任何表示式(除了未加括號的逗號表示式) |
[編輯] 解釋
[[assume]] 只能應用於空語句,如 [[assume(x > 0)]];。此語句稱為假定。
表示式被上下文轉換為bool,但它不被求值(它仍然是潛在求值)。
- 如果轉換後的 表示式 在假定出現的位置求值為 true,則假定沒有效果。
- 否則,假定的求值具有執行時未定義行為。
[編輯] 注意
由於假定如果不成立會導致執行時未定義行為,因此應謹慎使用。
一種正確的使用方法是在斷言之後使用假定
assert(x > 0); // trigger an assertion when NDEBUG is not defined and x > 0 is false [[assume(x > 0)]]; // provide optimization opportunities when NDEBUG is defined
[編輯] 示例
#include <cmath> void f(int& x, int y) { void g(int); void h(); [[assume(x > 0)]]; // Compiler may assume x is positive g(x / 2); // More efficient code possibly generated x = 3; int z = x; [[assume((h(), x == z))]]; // Compiler may assume x would have the same value after // calling h // The assumption does not cause a call to h h(); g(x); // Compiler may replace this with g(3); h(); g(x); // Compiler may NOT replace this with g(3); // An assumption applies only at the point where it appears z = std::abs(y); [[assume((g(z), true))]]; // Compiler may assume g(z) will return g(z); // Due to above and below assumptions, compiler may replace this with g(10); [[assume(y == -10)]]; // Undefined behavior if y != -10 at this point [[assume((x - 1) * 3 == 12)]]; g(x); // Compiler may replace this with g(5); }
[編輯] 缺陷報告
下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。
缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
---|---|---|---|
CWG 2924 | C++23 | 違反假定將導致未定義行為 | 導致執行時未定義行為 |
[編輯] 參考
- C++23 標準 (ISO/IEC 14882:2024)
- 9.12.3 假定屬性 [dcl.attr.assume]
[編輯] 參見
(C++23) |
標記不可達的執行點 (函式) |
contract_assert 語句 (C++26) |
在執行期間驗證內部條件 |
[編輯] 外部連結
1. | Clang 語言擴充套件文件:__builtin_assume 。 |
2. | Clang 屬性參考文件:assume 。 |
3. | MSVC 文件:__assume 內建函式。 |
4. | GCC 文件:__attribute__((assume(...))) 。 |