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

后端 未结 4 510
余生分开走
余生分开走 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:02

    There is almost no correct answer to this as it's almost totally style related, with the exception that if you think you may want to change from where you are going to import some declaration(s)/definition(s), in which case, when you use them, you don't specify any scope and import them using the using directive (to import a subset from the namespace) or the using namespace directive to import the entire set from the namespace.

    Mostly the using directive is used as a convenience directive, but it is a powerful way to direct which declarations/definitions are used. My preference is to not specify the scope and import the declarations. Doing this allows for easy changes if ever they are needed while reducing visual noise. Also, specifying the scope would mean I'd be "locked in" from where I am getting the declarations (well, I'd have to do a global search and replace to change it).

    If ever there is a conflict (you try an use a declared item with the same name that has been imported from more than one namespace) the compiler will let you know, so there's no real danger.

提交回复
热议问题