When would one use unnamed namespace in C++ ? Is it better in any sense than a free standing function? Also, should it be used only in source file and not in header file?
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.
Namespaces are used to organize code into logical groups and to prevent name collisions that can occur especially when your code base includes multiple libraries.
Advantages of namespace In one program, namespace can help define different scopes to provide scope to different identifiers declared within them. By using namespace - the same variable names may be reused in a different program.
A namespace with no identifier before an opening brace produces an unnamed namespace. Each translation unit may contain its own unique unnamed namespace. The following example demonstrates how unnamed namespaces are useful.
According to Stroustrup, you should use it in places where in old C you would have made static
globals. The idea is that the items in question can be "global" to the source file they are in, but not pollute the namespace of any other source files in your compilation.
In other words, you shouldn't be creating static
globals in C++. You should be using unnamed namespaces instead.
I have found some situations where they are useful in header files, but that should be rare. Mostly I think for declaring throwable exceptions. In that case the definitions in question will be global for everything that #include
s that header, but not for things that don't.
Unnamed namespace is private to the translation unit and this can be used to shield global variables and functions with same names occurring in different translation units so that no link conflicts arise.
For example, you need a class that will only be defined in a .cpp file and used only within that file. You want to call it CModuleLock
. If it is not in an unnamed namespace and some other .cpp file accidentially has another class CModuleLock
not in an unnamed namespace you won't be able to link your program.
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