When to use “::” for global scope in C++?

后端 未结 4 504
余生分开走
余生分开走 2020-12-18 20:11

Every once in a while, I stumble across some code that I\'m maintaining that challenges the way I think about my code style. Today was one of those days...

I\'m awa

4条回答
  •  情深已故
    2020-12-18 21:00

    Consider the following cases.

    Public library.

    You are writing an exportable library with public headers. And you absolutely have no clue in what environment your headers will be included. For example, someone may do:

    namespace std = my_space::std;
    #include "your_header"
    

    And all your definitions will be corrupted, if you simply use: std::list, etc. So, it's a good practice to prepend :: to everything global. This way you can be absolutely sure what you're using. Of course, you can do using (in C++11) or typedef - but it's a wrong way to go in headers.


    Collaborative .cc/.cpp files.

    Inside your own code that is not exposed to public in any way, but still editable not only by you - it's a good practice to announce, what you're going to use from outside of your namespace. Say, your project allows to use a number of vectors - not only an std::vector. Then, where it's appropriate, you put a using directive:

    // some includes
    
    using vector = ::std::vector;  // C++11
    typedef ::std::vector vector;  // C++03
    
    namespace my_namespace {
    ...
    }  // namespace my_namespace
    

    It may be put after all includes, or inside specific functions. It's not only gives control over the code, but also makes it readable and shortens expressions.

    Another common case - is a mixing of global C functions and a C++ code. It's not a good idea to do any typedefs with function names. In this situation you should prepend C functions with the global scope resolution operator :: - to avoid compilation problems, when someone implements a function with a same signature in the same namespace.

    Don't use :: for relative types and namespaces - or you'll lose the benefit of using namespaces at all.


    Your own code.

    Do what you want and how you want. There is only one good way - the way you fill comfortable with your own code. Really, don't bother about global scope resolution in this situation, if it's not requiered to resolve an ambiguity.

提交回复
热议问题