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?
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
#includes 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.
It’s used for name hiding. Each unnamed namespace is unique. The link here explains in more detail. It is typically used in a source file to hide functions that should only have internal linkage (e.g. not exposed to the outside world).
Unnamed namespaces are the “C++ version” of global static variables and functions. Note that you can also use a unnamed namespace for classes.
Basically, namespace solve the conflicts between the same name classes, identifiers, and function.for more information click on the link given below