C++ 属性: carries_dependency (始于 C++11)(C++26 中移除)
来自 cppreference.cn
< cpp | language | attributes
指示 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 依赖树中移除指定的对象 (函数模板) |