命名空间
变体
操作

C++ 属性: assume (自 C++23 起)

来自 cppreference.cn
< cpp‎ | language‎ | attributes
 
 
C++ 语言
通用主题
流程控制
条件执行语句
if
迭代语句(循环)
for
范围 for (C++11)
跳转语句
函数
函数声明
Lambda 函数表达式
inline 说明符
动态异常规范 (直到 C++17* 弃用)
noexcept 说明符 (C++11)
异常
命名空间
类型
说明符
const/volatile
decltype (C++11)
auto (C++11)
constexpr (C++11)
consteval (C++20)
constinit (C++20)
存储期说明符
初始化
 
 
属性
assume
(C++23)
(C++11)(直到 C++26)
(C++14)
(C++20)
(C++17)
(C++11)
(C++20)
 

指定给定的表达式在给定点始终求值为 true,以便允许编译器基于给定信息进行优化。

目录

[编辑] 语法

[[assume( 表达式 )]]
expression - 任何表达式(除了未加括号的 逗号表达式

[编辑] 解释

[[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++ 标准。

DR 应用于 已发布行为 正确行为
CWG 2924 C++23 违反假设将导致未定义行为 导致运行时未定义行为

[编辑] 参考文献

  • C++23 标准 (ISO/IEC 14882:2024)
  • 9.12.3 假设属性 [dcl.attr.assume]

[编辑] 参见

标记不可达的执行点
(函数) [编辑]
contract_assert 语句 (C++26) 验证执行期间的内部条件[编辑]

[编辑] 外部链接

1.  Clang 语言扩展文档:__builtin_assume
2.  Clang 属性参考文档:assume
3.  MSVC 文档:__assume 内置函数。
4.  GCC 文档:__attribute__((assume(...)))