Why does everybody use unanchored namespace declarations (i.e. std:: not ::std::)?

前端 未结 8 1849
悲&欢浪女
悲&欢浪女 2020-11-30 03:01

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 name

8条回答
  •  悲&欢浪女
    2020-11-30 03:39

    A lot of code is written in the global namespace. If someone really redefines ::std::, it won't matter how you refer to it in that kind of code.

    Also, your scenario is both unlikely and easy to work around. Firstly, the convention since there was a 'std' was that you don't use that name. Secondly, if you were to encounter a package that defined the 'std' namespace, you just do this:

    #include 
    
    namespace package_name {
      using namespace std;
    }
    
    namespace my_app {
      class my_class : public package_name::class_of_something {};
    }
    

    Or something similar. You might have to explicitly name ::std as std. My point is this: people go about using the un-anchored 'std::' all the time because even the worst-case consequences aren't a big deal, and unlikely at that.

提交回复
热议问题