Const constant in namespace

I know that members of a static const class can only be initialized in headers. Is it the same for namespaces? For example, is it permissible to write:

namehuman.hpp

 namespace namehuman { string const human("human"); } 

main.cpp

 #include "namehuman.hpp" cout << namehuman::human << endl; 

I am wondering if all the files, including the header file, will have their own copy of the person’s string , or if the person will be a real global variable (not copied many times). To avoid every file making a copy of it, am I obliged to use extern ?

+5
source share
2 answers

Constants have an internal relationship. Thus, any compilation unit that includes a header with a constant definition will have its own instance of the object.

In accordance with the C ++ standard (3.5 Program and communication)

3 A name that has a namespace scope (3.3.6) has an internal relationship if it is a name

...

- a non-volatile variable that is explicitly declared as const or constexpr and not one explicitly declared extern, nor previously stated that it has an external connection; or

If you want a constant with external coupling, you must declare it as an extern specifier and define it in a compilation unit.

+4
source

I think that it will define human several times, so it may happen that this leads to an ODR violation (see below). It's usually best to declare it in the title.

 extern const string human; 

and add the definition to the implementation file

 string human("human"); 

Be careful with the initialization order fiasco and equivalent when closing the application.

An ODR violation can be caused when the built-in function with the ODR of the external connection uses human . I think that since it is really easy to do, and there is no way to protect it, it is best to define constant lines in the implementation file.

+1
source

Source: https://habr.com/ru/post/1234745/


All Articles