When using an unnamed namespace are there any issues if it is nested within another namespace? For example, is there any real difference between Foo1.cpp and Foo2.cpp in the following code:
// Foo.h namespace Foo { void fooFunc(); } // Foo1.cpp namespace Foo { namespace { void privateFunction() { ... } } void fooFunc() { privateFunction(); } } // Foo2.cpp namespace { void privateFunction() { ... } } namespace Foo { void fooFunc() { privateFunction(); } }
Unnamed NamespacesThey 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.
In C++, namespaces can be nested, and resolution of namespace variables is hierarchical. For example, in the following code, namespace inner is created inside namespace outer, which is inside the global namespace.
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.
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. There is no runtime or compile time performance difference.
Unnamed namespace could be considered as a normal namespace with unique name which you do not know. According to C++ Standard 7.3.1.1:
An unnamed-namespace-definition behaves as if it were replaced by
namespace unique { /* empty body */ } using namespace unique; namespace unique { namespace-body }
where all occurrences of unique in a translation unit are replaced by the same identifier and this identifier differs from all other identifiers in the entire program.
There are no additional issues.
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