Search code examples
c++namespacesunnamed-namespace

Unnecessary use of unnamed namespaces C++


I keep seeing code like this everywhere in my company:

namespace {

const MAX_LIMIT = 50;
const std::string TOKEN = "Token";

}

I am confused as of why you need an anonymous namespace here. On one hand, you want a local translation unit for MAX_LIMIT AND TOKEN. But that is already achieved without the anonymous namespace due to the const. static const and simple const both achieve local translation unit.

On the other hand, you don't have naming clashes if somewhere in your file you have a variable named the same.

int foo()
{
std::string TOKEN = "MyToken"; // Clash! ::TOKEN vs TOKEN can be used.
}

That would justify the anonymous namespace. But how often you you need a variable name in your function that is actually taken already by a const variable declared outside your function? My answer is never. So in practice, for me the unnamed namespace is not needed. Any hints?


Solution

  • 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.