Why is std:: used by experienced coders rather than using namespace std;? [duplicate]

时光怂恿深爱的人放手 提交于 2019-11-29 09:41:37
LumpN

From C++ FAQ:

Should I use using namespace std in my code?

Probably not.

People don't like typing std:: over and over, and they discover that using namespace std lets the compiler see any std name, even if unqualified. The fly in that ointment is that it lets the compiler see any std name, even the ones you didn't think about. In other words, it can create name conflicts and ambiguities.

https://isocpp.org/wiki/faq/coding-standards#using-namespace-std

Simply put, you are less likely to use the wrong types or functions by mistake, or name conflicts. Say you are using your own math library, plus std, and declare using both of them, in some arbitrary order. Now, they both define function pow. Which pow are you using when you invoke pow? I think it is worth the extra typing.

Philipp

I don't think it's the case that more experienced programmers use explicit namespaces, see e.g. Do you prefer explicit namespaces or 'using' in C++?

Note however that you should never import namespaces in header files and that in some cases explicit namespaces are clearer, for example with the functions std::min() and std::max()

I think it is some what a preference thing. Some people like to see the explicit namespaces when using the classes. One exception is I never to use a using namespace std in a header file. As this can unexpectedly change the behaviour of a class that is using this header file.

Experienced programmers use whatever solves their problems and avoid whatever creates new problems.

Thus they avoid header-file-level using-directives for obvious reason.

And they try to avoid full qualification of names inside their source files. Minor point is that it's not elegant to write more code when less code suffice without good reason. Major point is turning off ADL.

What are these good reasons? Sometimes you explicitly want turning off ADL. Sometime you want to disambiguate.

So following are ok: 1) function-level using-directives and using-declarations inside functions' implementations; 2) source-file-level using-declarations inside source files; 3) (sometimes) source-file-level using-directives.

Namespace(s) are additional qualifiers for our variables. Lets say we have 'string' defined in std and now if we define a 'string' in mynamespacealso.

Now, if I write using namespace std;at the top of a file, then from there onwards a string becomes ambiguous for a compiler.

One can however take a middle approach, of strictly not having using namespace std;in a header(.h) file, since others might want to use your class and can get conflicts. While for an implementation (.cxx) file, you can be careful to use it if you are sure there won't be any conflicts.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!