Why Are Unnamed Namespaces Used and What Are Their Benefits

Why are unnamed namespaces used and what are their benefits?

Unnamed namespaces are a utility to make an identifier translation unit local. They behave as if you would choose a unique name per translation unit for a namespace:

namespace unique { /* empty */ }
using namespace unique;
namespace unique { /* namespace body. stuff in here */ }

The extra step using the empty body is important, so you can already refer within the namespace body to identifiers like ::name that are defined in that namespace, since the using directive already took place.

This means you can have free functions called (for example) help that can exist in multiple translation units, and they won't clash at link time. The effect is almost identical to using the static keyword used in C which you can put in in the declaration of identifiers. Unnamed namespaces are a superior alternative, being able to even make a type translation unit local.

namespace { int a1; }
static int a2;

Both a's are translation unit local and won't clash at link time. But the difference is that the a1 in the anonymous namespace gets a unique name.

Read the excellent article at comeau-computing Why is an unnamed namespace used instead of static? (Archive.org mirror).

Uses of unnamed namespace in C++

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/anonymous namespaces vs. static functions

The C++ Standard reads in section 7.3.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.

Edit:

The decision to deprecate this use of the static keyword (affecting visibility of a variable declaration in a translation unit) has been reversed (ref). In this case using a static or an unnamed namespace are back to being essentially two ways of doing the exact same thing. For more discussion please see this SO question.

Unnamed namespace's still have the advantage of allowing you to define translation-unit-local types. Please see this SO question for more details.

Credit goes to Mike Percy for bringing this to my attention.

Unnamed namespace Vs Global declaration

The point of an unnamed namespace is to provide a unique namespace within a translation unit (= a source file) without requiring an explicit prefix. This allows you to guarantee that your global names won't clash with other, equal global names in other translation units.

For example:

// file1.cpp

namespace
{
void foo() { /* ... */ }
}

#include "bar.h"

int do_stuff()
{
foo();
bar();
return 5;
}

// file2.cpp

namespace
{
void foo() { /* ... */ }
}

#include "bar.h"

int do_something else()
{
bar();
foo();
return 12;
}

You can link those two translation units together and know for certain that the two names foo will refer to the function defined in the respective file, and you do not violate the one-definition rule.

Technically, you can think of an unnamed namespace as something like this:

namespace unique_and_unknowable_name
{
// ...
}

using namespace unique_and_unknowable_name;

Without this tool, the only way you could guarantee a non-violation of ODR would be to use static declarations. However, there's a subtle difference, in that static affects linkage, while namespaces do not.

Unnecessary use of unnamed namespaces C++

In this particular case, the namespace is indeed redundant, because the const namespace scope variables indeed have internal linkage by default.

Consider the possibility of changing the code later. Perhaps one of the variables shouldn't be const after all. But making it non-const also changes the default linkage. The anonymous namespace would keep the internal linkage even after such change. In other words, the anon namespace separates the concerns over constness and the linkage. Whether that's a good thing, depends on the context.

Note that same thing can be achieved by using static keyword. Since this has exactly the same effect as the anon namespace, the choice is mostly aesthetic and therefore opinion based.

An argument for using anon namespaces instead of static could be consistency. You cannot define types with internal linkage with static. Since some internal symbols (types) cannot be defined outside an anonymous namespace, you could have a convention to define all internal symbols in an anonymous namespace. Of course, such convention would be - as conventions typically are - a matter of taste.

Your second counter argument seems to be arguing against a difference that doesn't exist. The anonymous namespace makes no difference to name hiding within function scope.

What does putting a structure in an anonymous namespace do?

Everything that's declared inside an anonymous namespace gets a unique, unknowable name, and thus cannot be referred to from any other translation unit. The anonymous namespace is thus guaranteed to be local to the current translation unit only, and never to clash with a different one.

For example, if you say namespace { int i; }, you are guaranteed that only the current translation unit sees the global i. Even if this declaration is in a header that's included in multiple, different TUs, each TU receives its own copy of the global variable (each with a different, unknowable fully-qualified name).

The effect was similar to declaring a global object static (which gives the global object internal linkage) in C++03, where objects in the anonymous namespace may still have external linkage. In C++11, names in an unnamed namespace have internal linkage as per 3.5/4, so the effect is exactly the same for variables and functions as declaring them static – but internal linkage applies to more than just variables and functions (e.g. enums, classes, templates), so as of C++11, you should always prefer unnamed namespaces!

Why are namespaces used?

For small, self-contained projects, there's not much need for namespaces, and you'd never create a namespace for each object or concept in your code.

Larger projects using libraries benefit from being isolated from names introduced by those libraries, as well as some internal organisation to make readability easier.

Similarly, when creating a library, it's a good idea to put its contents into a namespace so as not to cause headaches and conflicts for your users (as you don't know how large their projects will be, and what names they may want to use themselves).

To use an analogy: if you have three books, you don't bother organising them alphabetically. But, once you have a hundred, you might decide to categorise them on your bookshelf for easier reference and mental health.

And, if you now borrow another twenty books from a friend, you'd probably keep those in a separate pile so they're easier to find when you need to give them back.

So, to some degree, this is a case of… you'll know why you need it, when you need it.

Unnamed namespaces vs private variables

They aren't the same.

Integer i in the anonymous namespace will be shared by all instances of MyClass.

The private integer i in MyClass will be unique for each instantiation of the class.

The equivalent using private would be to make i static:

//.h
class MyClass
{
private:
static int i;
};

And instantiate the one single shared i like this:

//.cpp
int MyClass::i = 0;

Are static or unnamed namespace still useful when header and implementation are separated?

Keeping a definition in implementation file does not make it private in any sense. Any other header or implementation file can declare that function and use it. It's not always a bad thing - I used parts of private implementations of libraries when I really needed it (but I do not recommend doing that).

The worse part of having such not-so-private implementation is its potential for One Definition Rule violation. ODR states that every* function or variable must have exactly one definition in the whole program. If there is more than one definition, behaviour is undefined**.

This means that when you have your not-so-private implementation in your file and nobody knows about it, they can unknowingly write a function with the same name and arguments and get an ODR violation.

It would be a good practice to use static or anonymous namespace for all free functions that should be limited to a single file. Functions that need to be used from other files cannot use this strategy, so to limit the risk of ODR violations you should use descriptive names and perhaps (named) namespaces. Just make sure you don't overuse namespaces.


Note: using anonymous namespaces doesn't make sense in header files. Anonymous namespace limits the scope of its content to the translation unit in which it exists, but header files are copied and pasted into (potentially) multiple TUs. The one use of anonymous namespaces is in header-only libraries, as described in this question - it allows to create global objects in header file without ODR violation (but at a cost that each TU has its own copy of that variable).


*except for template functions, inline functions, functions defined in class definition and a couple more. Even then, all definitions must be exactly the same.

**When I encountered it once, linker used random definition, whichever it saw at that moment. Hilarity and long debugging sessions ensued.



Related Topics



Leave a reply



Submit