Unnamed Namespaces They are directly usable in the same program and are used for declaring unique identifiers. In unnamed namespaces, name of the namespace in not mentioned in the declaration of namespace. The name of the namespace is uniquely generated by the compiler.
1.1 Unnamed namespaces, paragraph 2: The use of the static keyword is deprecated when declaring objects in a namespace scope, the unnamed-namespace provides a superior alternative. Static only applies to names of objects, functions, and anonymous unions, not to type declarations.
Do not define an unnamed namespace in a header file. When an unnamed namespace is defined in a header file, it can lead to surprising results. Due to default internal linkage, each translation unit will define its own unique instance of members of the unnamed namespace that are ODR-used within that translation unit.
An anonymous namespace makes the enclosed variables, functions, classes, etc. available only inside that file. In your example it's a way to avoid global variables.
Some code I've been asked to modify looks rather like this:
namespace XXX {
namespace {
// some stuff
} // end of unnamed
// Some stuff within the scope of XXX
} // end of XXX
I'm struggling to see the advantage, if any, of embedding the unnamed namespace within another namespace and I'm considering changing it to:
namespace {
// some stuff
} // end of unnamed
namespace XXX {
// Some stuff within the scope of XXX
} // end of XXX
Any views would be gratefully appreciated.
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