命名空间
变体
操作

C++ 属性: carries_dependency (始于 C++11)(C++26 中移除)

来自 cppreference.cn
< cpp‎ | language‎ | attributes
 
 
C++ 语言
通用主题
流程控制
条件执行语句
if
迭代语句(循环)
for
range-for (C++11)
跳转语句
函数
函数声明
Lambda 函数表达式
inline 说明符
动态异常规范 在 C++11 中弃用*
noexcept 说明符 (C++11)
异常
命名空间
类型
说明符
const/volatile
decltype (C++11)
auto (C++11)
constexpr (C++11)
consteval (C++20)
constinit (C++20)
存储期说明符
初始化
表达式
替代表示
字面量
布尔字面量 - 整数字面量 - 浮点字面量
字符字面量 - 字符串字面量 - nullptr (C++11)
用户自定义字面量 (C++11)
实用工具
属性 (C++11)
类型
typedef 声明
类型别名声明 (C++11)
类型转换
内存分配
类特定的函数属性
虚函数
override 说明符 (C++11)  
final 说明符 (C++11)
explicit (C++11)
static

特殊成员函数
模板
模板特化
参数包 (C++11)
杂项
 
 
属性
(C++23)
carries_dependency
(C++11)(until C++26)
(C++14)
(C++17)
(C++26)
(C++20)
(C++17)
(C++17)
(C++11)
(C++20)
 

指示 release-consume std::memory_order 中的依赖链在函数内外传播,这允许编译器跳过不必要的内存栅栏指令。

目录

[编辑] 语法

[[carries_dependency]]

[编辑] 解释

此属性可能出现在两种情况中

1) 它可以应用于函数或 lambda 表达式的参数声明,在这种情况下,它指示参数的初始化将依赖关系带入该对象的左值到右值转换。
2) 它可以应用于整个函数声明,在这种情况下,它指示返回值将依赖关系带到函数调用表达式的求值。

此属性必须出现在任何翻译单元中函数或其参数的首次声明中。如果在另一个翻译单元中函数或其参数的首次声明中未使用它,则程序是非良构的;不需要诊断。

[编辑] 示例

几乎未作修改地改编自 SO

#include <atomic>
#include <iostream>
 
void print(int* val)
{
    std::cout << *val << std::endl;
}
 
void print2(int* val [[carries_dependency]])
{
    std::cout << *val << std::endl;
}
 
int main()
{
    int x{42};
    std::atomic<int*> p = &x;
    int* local = p.load(std::memory_order_consume);
 
    if (local)
    {
        // The dependency is explicit, so the compiler knows that local is
        // dereferenced, and that it must ensure that the dependency chain
        // is preserved in order to avoid a fence (on some architectures).
        std::cout << *local << std::endl;
    }
 
    if (local)
    {
        // The definition of print is opaque (assuming it is not inlined),
        // so the compiler must issue a fence in order to ensure that
        // reading *p in print returns the correct value.
        print(local);
    }
 
    if (local)
    {
        // The compiler can assume that although print2 is also opaque then
        // the dependency from the parameter to the dereferenced value is
        // preserved in the instruction stream, and no fence is necessary (on
        // some architectures). Obviously, the definition of print2 must actually
        // preserve this dependency, so the attribute will also impact the
        // generated code for print2.
        print2(local);
    }
}

可能的输出

42
42
42

[编辑] 参考

  • C++23 标准 (ISO/IEC 14882:2024)
  • 9.12.4 carries_dependency 属性 [dcl.attr.depend]
  • C++20 标准 (ISO/IEC 14882:2020)
  • 9.12.3 carries_dependency 属性 [dcl.attr.depend]
  • C++17 标准 (ISO/IEC 14882:2017)
  • 10.6.3 carries_dependency 属性 [dcl.attr.depend]
  • C++14 标准 (ISO/IEC 14882:2014)
  • 7.6.4 carries_dependency 属性 [dcl.attr.depend]
  • C++11 标准 (ISO/IEC 14882:2011)
  • 7.6.4 carries_dependency 属性 [dcl.attr.depend]

[编辑] 参见

(C++11)(在 C++26 中弃用)
从 std::memory_order_consume 依赖树中移除指定的对象
(函数模板) [编辑]