C++: What's happen when I use “using namespace xyz” before #include<headerxy> [duplicate]

只愿长相守 提交于 2019-12-23 16:26:48

问题


Possible Duplicate:
Ordering of using namespace std; and includes?

I heard that it is strongly prohibited to use "using namespace xy" before "#include ". E.g.

#include <iostream>

using namespace std;

int main() {
...
}

What's the technical reason for that? I tried following and it worked without any problems:

using namespace std;

#include <iostream>

int main() {
....
}

回答1:


No, it is not strongly prohibited (otherwise it would be a compilation or preprocessing error).

The using keyword puts all functions and variable into the current namespace, and it is discouraged to use it in the header files.




回答2:


I can think of one good reason. It is that if the namespace hasn't already been declared, the statement is illegal. At least by my reading of the standard; most compilers seem to treat the using directive (using namespace name;) as if it was a declaration of the namespace, although there's nothing in the standard that I can find to justify this.

More generally, it's best to avoid namespace directives as much as possible, except in very limited scopes (and I'd never use a namespace directive for std, because there's just too much in it which would get drawn in).




回答3:


The technical reason is that using will only import anything that is currently visible into the current namespace.

If you're includeing a file after using, you introduce a "weird" order dependency. Of course, this could be what you want, so it is not forbidden by the language. However, you're effectively changing the meaning of headers you're including after the using, since you're exposing the header to a different context (and name lookup might find other names, depending on the context). Name lookup rules can sometimes be subtle, and you don't want to introduce subtleties in someone else's code.

There's an excellent discussion of this in the book "C++ Coding Standards" (Sutter, Alexandrescu), Chapter 59: "Don't write namespace usings in a header file or before an #include"



来源:https://stackoverflow.com/questions/6895020/c-whats-happen-when-i-use-using-namespace-xyz-before-includeheaderxy

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