名稱空間
變體
操作

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

來自 cppreference.com
< 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 依賴樹中移除指定的物件
(函式模板) [編輯]