命名空间
变体
操作

C++ 属性: carries_dependency (C++11 起)(C++26 移除)

来自 cppreference.cn
< cpp‎ | 语言‎ | 属性
 
 
C++ 语言
 
 
属性
(C++23)
carries_dependency
(C++11)(直至 C++26)
(C++14)
(C++20)
(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 携带依赖属性 [dcl.attr.depend]
  • C++20 标准 (ISO/IEC 14882:2020)
  • 9.12.3 携带依赖属性 [dcl.attr.depend]
  • C++17 标准 (ISO/IEC 14882:2017)
  • 10.6.3 携带依赖属性 [dcl.attr.depend]
  • C++14 标准 (ISO/IEC 14882:2014)
  • 7.6.4 携带依赖属性 [dcl.attr.depend]
  • C++11 标准 (ISO/IEC 14882:2011)
  • 7.6.4 携带依赖属性 [dcl.attr.depend]

[编辑] 参阅

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