I read that C++11 has introduced the concept of attributes for example [[noreturn]]
which is to indicate that the function doesn not return to the caller.
[[noreturn]] void fun()
{
throw std::string("Error!!!");
}
void func()
{
fun();
}
void aTempFunc()
{
try
{
func();
}
catch (std::string &e)
{
std::cout << e << std::endl;
}
}
By looking at the example the reader can understand that the function throws an exception and call will not be returned to the func
function.
I am bit confused to understand what are C++ attributes and why it is required? How a programmer can really make use of these attributes?
Can someone explain in detail. Please correct me if my understanding about the attributes is wrong. Thanks.
Attributes are a mechanism by which the developer can attach extra information to language entities with a generalized syntax, instead of introducing new syntactic constructs or keywords for each feature.
Attributes and methods are basically variables and functions that belongs to the class. These are often referred to as "class members". A class is a user-defined data type that we can use in our program, and it works as an object constructor, or a "blueprint" for creating objects.
Most of the attributes are compiler hint, ABI specification or requirement relative to the target object format (visibility, section, etc.).
So most attributes do not change the observable behavior of your program: if you remove all the attributes of your source code, and if it compiles, you can reasonably expect to have a resulting program behaving as the one compiled with the attributes.
But there are also attributes that can noticeably affect the behavior or compilability of your program, for example the align
attribute, even if they do not change drastically the semantic of your code.
Implementation can provide their own attributes, and these attributes can have any consequence as long as the observable behaviors of the program follow the c++ language, C++ standard[intro.compliance]:
A conforming implementation may have extensions (including additional library functions), provided they do not alter the behavior of any well-formed program. Implementations are required to diagnose programs that use such extensions that are ill-formed according to this document. Having done so, however, they can compile and execute such programs.
attributes are put by the programmer, for the compiler benefit. Basically, they give the compiler more information and allow for more optimization.
For example the noreturn
attribute allow the compiler to reclaim stack memory before calling the function (because you will not need the stack frames again) or at least consider the code following the call as dead code.
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