屬性指定符序列(C23 起)
為型別、物件、表示式等引入實現定義的屬性。
目錄 |
[編輯] 語法
[[
attr ]]
[[
attr1, attr2, attr3(
args)
]]
[[
attribute-prefix::
attr (
args)
]]
形式上,語法是
[[ attribute-list ]] |
(自 C23 起) | ||||||||
其中 attribute-list 是由零個或多個 attribute-token 以逗號分隔的序列
standard-attribute | (1) | ||||||||
attribute-prefix :: identifier |
(2) | ||||||||
standard-attribute ( argument-list (可選) ) |
(3) | ||||||||
attribute-prefix :: identifier ( argument-list (可選) ) |
(4) | ||||||||
其中 attribute-prefix 是一個 identifier,argument-list 是一個由括號、方括號和花括號平衡的詞法單元序列(balanced-token-sequence)。
[編輯] 解釋
屬性為實現定義的語言擴充套件提供了統一的標準語法,例如 GNU 和 IBM 語言擴充套件 __attribute__((...))
、Microsoft 擴充套件 __declspec()
等。
屬性幾乎可以在 C 程式的任何地方使用,並且可以應用於幾乎所有事物:型別、變數、函式、名稱、程式碼塊、整個翻譯單元,儘管每個特定屬性僅在實現允許的地方有效:[[expect_true]]
可能是一個只能與 if 一起使用的屬性,而不能與類宣告一起使用。[[omp::parallel()]]
可能是一個應用於程式碼塊或 for 迴圈的屬性,但不能應用於型別 int
等。(請注意,這兩個屬性是虛構示例,標準和一些非標準屬性請參見下文)
在宣告中,屬性可以出現在整個宣告之前,也可以直接出現在所宣告實體名稱之後,在這種情況下它們會結合。在大多數其他情況下,屬性應用於直接前面的實體。
兩個連續的左方括號詞法單元([[
)只能在引入屬性指定符或在屬性引數內部出現。
除了下面列出的標準屬性外,實現可能支援具有實現定義行為的任意非標準屬性。所有實現未知的屬性都將被忽略,不會導致錯誤。
每個 標準屬性 都保留用於標準化。也就是說,每個非標準屬性都以實現提供的 attribute-prefix 為字首,例如 [[gnu::may_alias]]
和 [[clang::no_sanitize]]
。
[編輯] 標準屬性
C 標準僅定義以下屬性。每個名稱形式為 attr
的標準屬性也可以拼寫為 __attr__
,其含義不變。
[[deprecated]] (C23)[[deprecated("reason")]] (C23){{{notes}}} |
表示允許使用此屬性宣告的名稱或實體,但由於某種原因不鼓勵使用 (屬性指定符) |
[[fallthrough]] (C23) |
指示從前一個 case 標籤的直落是故意的,不應被警告直落的編譯器診斷 (屬性指定符) |
鼓勵編譯器在返回值被丟棄時發出警告 (屬性指定符) | |
[[maybe_unused]] (C23) |
抑制(如果有)未使用的實體的編譯器警告 (屬性指定符) |
指示函式不返回 (屬性指定符) | |
[[unsequenced]] (C23) |
表示函式是無狀態、無效果、冪等的且獨立的 (屬性指定符) |
[[reproducible]] (C23) |
表示函式是無效果且冪等的 (屬性指定符) |
[編輯] 屬性測試
__has_c_attribute( attribute-token ) |
|||||||||
檢查是否存在由 attribute-token 命名的屬性詞法單元。
對於標準屬性,它將擴充套件為該屬性新增到工作草案的年份和月份(參見下表),供應商特定屬性的存在由非零整數常量確定。
__has_c_attribute
可以在 #if 和 #elif 的表示式中展開。它被 #ifdef、#ifndef 和 defined 視為已定義宏,但不能在其他任何地方使用。
屬性詞法單元 | 屬性 | 值 | 標準 |
---|---|---|---|
deprecated
|
[[deprecated]]
|
201904L | (C23) |
fallthrough
|
[[fallthrough]]
|
201904L | (C23) |
maybe_unused
|
[[maybe_unused]]
|
201904L | (C23) |
nodiscard
|
[[nodiscard]]
|
202003L | (C23) |
noreturn _Noreturn
|
[[noreturn]] [[_Noreturn]]
|
202202L | (C23) |
unsequenced
|
[[unsequenced]]
|
202207L | (C23) |
reproducible
|
[[reproducible]]
|
202207L | (C23) |
[編輯] 示例
[[gnu::hot]] [[gnu::const]] [[nodiscard]] int f(void); // declare f with three attributes [[gnu::const, gnu::hot, nodiscard]] int f(void); // the same as above, but uses a single attr // specifier that contains three attributes int f(void) { return 0; } int main(void) { }
[編輯] 參考文獻
- C23 標準 (ISO/IEC 9899:2024)
- 6.7.12 屬性 (p: 待定)
[編輯] 另請參見
C++ 文件,關於 屬性指定符序列
|
[編輯] 外部連結
1. | GCC 中的屬性 |
2. | Clang 中的屬性 |