What this C++11 syntax means?
[[ noreturn ]] void f () {
throw "error";
}
The C++ Standard Working Draft n3797 states,
The first declaration of a function shall specify the noreturn attribute if any declaration of that function specifies the noreturn attribute. If a function is declared with the
noreturn
attribute in one translation unit and the same function is declared without the noreturn attribute in another translation unit, the program is ill-formed; no diagnostic required.
What is meant by an attribute of a function?
A function is defined by its name, its return type, and a list of formal parameters, along with their types. These items constitute the "interface" of the function: they are important to the caller of the function, because they define the way to invoke it.
Attributes, on the other hand, provide a way to tell the compiler additional things about the function that do not alter its interface. When the compiler knows that a function is
fork
), orthe compiler can optimize the code better, and provide additional warnings / silence unnecessary warnings.
For example, if you write
main() {
f();
g();
}
and f()
is marked noreturn
, the compiler will issue a warning about the call of g()
being unreachable.
Attributes are a new feature in C++11. Compiler vendors have long offered vendor-specific extensions that allow you to annotate functions in some way or another, but now there is a standard mechanism. There aren't many actual attributes specified by the standard (only noreturn
and carries_dependency
), but the mechanism for annotating functions is standardized now at least.
That said, the noreturn
attribute has non-trivial semantics: If a function declared with this attribute does actually return, the program has undefined behaviour. Compilers should (but don't have to) produce a diagnostic if they can tell that you are returning from a noreturn function. The attribute is valuable to allow optimizations and better diagnostics.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With