Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uses of unnamed namespace in C++

Tags:

c++

namespaces

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?

like image 804
Asha Avatar asked Mar 15 '11 13:03

Asha


People also ask

What is the use of unnamed namespace?

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.

What is the purpose of namespace in C?

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.

What is the benefits of using namespace?

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.

What are anonymous namespaces C++?

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.


2 Answers

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.

like image 65
T.E.D. Avatar answered Oct 11 '22 02:10

T.E.D.


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.

like image 32
sharptooth Avatar answered Oct 11 '22 04:10

sharptooth