C++ – Why does everybody use unanchored namespace declarations (i.e. std:: not ::std::)

cnamespaces

It seems to me that using unanchored namespaces is just asking for trouble later when someone puts in a new namespace that happens to have the same name as a root level namespace and mysteriously alters the meaning of a whole lot of programs. So, why do people always say std:: instead of ::std::. Do they really mean to be saying "I want to use whatever std is handy, not the root one."?

Here is an example of what I mean:

In fred/Foo.h:

#include <string>

namespace fred {

class Foo {
 public:
   void aPublicMember(const std::string &s);
};

} // end namespace fred

In fred/Bar.h:

namespace fred {
namespace std {  // A standard fred component

class string { // Something rather unlike the ::std::string
   // ...
};

} // namespace std

class Bar {
 public:
   void aPublicMember(std::string &s);
};

} // namespace fred

In oops.cpp:

#include <string>
#include "fred/Bar.h"
#include "fred/Foo.h"  // Oops, the meaning of Foo is now different.

Is that what people want, or am I missing something?

And maybe you say that you should just never name a namespace std. And that's all well and good, but what about some other root level namespace then? Should any root level namespace anybody ever defines anywhere always be off-limits for a sub-namespace name?

To clarify, I won't consider any answer that tells me std is special because I just used it as an example. I'm talking about a general issue, and I'm using std as a prop to illustrate it, though I do admit it's a rather startling prop.

Best Answer

The practical reason for unanchored namespaces is that one level of namespaces usually is enough. When it isn't, a second level is usually going to be used for implementation details. And finally, even when using multiple levels, they are still usually specified implicitly from root level. ie. even inside namespace ns1, you'd typically refer to ns1::ns2::foo instead of ns2::foo or ::ns1::ns2::foo.

So, for these three reasons the ::ns1 form is redundant in normal cases. The only case where I'd consider it would be in submissions to Boost, because as a Boost author I won't know where my software will be used.