Introduction to Attributes
Get a brief introduction to attributes that come with C++20.
With C++20, we get new and improved attributes such as [[nodiscard("reason")]]
, [[likely]]
, [[unlikely]]
, and [[no_unique_address]]
. In particular, [[nodiscard("reason")]]
can be used to explicitly express the intent of our interface.
🔑 Attributes
Attributes allow the programmer to express additional constraints on the source code or give the compiler additional optimization possibilities. You can use attributes for types, variables, functions, names, and code blocks. When you use more than one attribute, you can apply each one after the other (
func1
) or all together in one attribute, separated by commas (func2
) as follows:[[attribute1]] [[attribute2]] [[attribute3]] int func1(); [[attribute1, attribute2, attribute3]] int func2();
Attributes can be implementation-defined language extension or standard attributes, such as the following list of attributes C++11 - C++17 already have:
[[noreturn]]
(C++11): indicates that the function does not return[[carries_dependency]]
(C++11): indicates a dependency chain in release-consume ordering[[deprecated]]
(C++14): indicates that you should not use a name[[fallthrough]]
(C++17): indicates that a fallthrough in a case branch is intentional[[maybe_unused]]
(C++17): suppresses compiler warnings about used names
Get hands-on with 1400+ tech skills courses.