Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unnecessary use of unnamed namespaces C++ [closed]

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?

like image 799
FCR Avatar asked May 12 '16 09:05

FCR


2 Answers

The namespace is redundant as you explain. You could remove the namespace { and matching } .

One difference is that you could have distinct names ::TOKEN and unnamed_namespace::TOKEN. But that probably just adds confusion and it'd be better to get a compilation error.

Not sure what the second half of your post is about, local variable TOKEN shadows both ::TOKEN and unnamed_namespace::TOKEN. So the change would make no difference to that case.

like image 107
M.M Avatar answered Sep 21 '22 00:09

M.M


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.

like image 27
eerorika Avatar answered Sep 22 '22 00:09

eerorika