c++namespacesscope-resolutionglobal-namespace

Is there any difference between qualified ::toplevel_namespace and unqualified toplevel_namespace?


Generally, the difference between ::any_name and any_name should be clear. If preceded by :: the name is always and only looked up in the global namespace.

I was wondering however whether there is an technical(*) difference, given a namespace that I already know to be toplevel (i.e. directly below the global namespace) and where I know that there is no second (nested) namespace (or any name) of the same name.

For example, is there any difference between using ::std::string vs. std::string?


(*) Readability, style and maintenance issues aside.


Solution

  • "For example, is there any difference between using ::std::string vs. std::string?"

    Think about such weird situation

    LegacyString.hpp

    namespace Legacy {
        namespace std {
            class string {
                // ...
            };
        }
    }
    

    #include <string>
    #include "LegacyString.hpp"
    
    using namespace Legacy;
    

    In this case it would certainly make a difference if you say ::std::string or just std::string in the following code.

    And yes, as also stated in your other question's accepted answer, it's perfectly legal to name any construct, be it namespace, class, struct, typedef, etc. std.


    As for your question edits:

    "and where I know that there is no second (nested) namespace (or any name) of the same name."

    If you know this is the case, the both forms are equivalent of course. As you mentioned the resolving of namespaces ends up at global level and will resolve it correctly without the prefixed ::.

    IMHO usually we rely on, that at least no one is that stupid, to name any construct std actually. But to cite Einstein:

    "Two things are infinite: the universe and human stupidity; and I'm not sure about the the universe."