using namespace std;的注意事项

作者:zhang.jingjing
链接:转自  https://www.zhihu.com/question/26911239/answer/51503880
来源:知乎


因为使用STL中 有部分名称是没有加下划线的保留标记的
而在自己的源代码中用到了后会引发未定义的后果

例如:
#include <algorithm>
using namespace std;
int main()
{
	int max=0;
}


一直我都告诫学习C++的人 以后精通了C++就不要用using namespace std;
如使用 如using std::cin;效果会更好


原例子已删除:未经证实
例子原文放在最后


----update:Jun 18th , 2015

看来论据不够充分 那我加下

《C++ Primer Plus (第六版 中文版 人民邮电出版社)》第九章:内存模型和名称空间 第328页:
"有关using编译命令和using声明,需要记住的一点是,他们增加了名称冲突的可能性。"

《C++ Primer Plus (第六版 中文版 人民邮电出版社)》第九章:内存模型和名称空间 第329页:
一般说来,使用using命令使用using编译命令安全,这是由于它只导入了制定的名称。如果该名称与局部名称发生冲突,编译器将发出指示。using编译命令导入所有的名称,包括可能并不需要的名称。如果与局部名称发生冲突,则局部名称将覆盖名称空间版本,而编译器并不会发出警告。另外,名称空间的开放性意味着名称空间的名称可能分散在多个地方,这使得难以准确知道添加了哪些名称。
...
然而名称空间的支持者希望有更多的选择,既可以使用解析运算符面也可以使用using声明,也就是说,不要这样做:
using namespace std; // avoid as too indiscriminate(随意)
而应这样做
int x;
std::cin >> x ;
std::cout << x << std::endl;
或者这样做
using std::cin;
using std::cout;
using std::endl;
int x;
cin >> x;
cout << x << endl;

《C++ Primer Plus (第六版 中文版 人民邮电出版社)》附录I: 转换为ISO标准的C++ 第915页:
名称空间有助于组织程序中使用标识符,避免名称冲突。由于标准库是使用性的头文件组织实现的,它将名称放在std名称空间中,因此使用这些头文件需要处理名称空间。
出于简化的目的,本书的事例通常使用编译命令using来使std名称空间中名称可用:
#include <iostream>
#include <string>
#include <vector>
using namespace std;    //a using-directive
然而,不管需要于否,都导出名称空间中的所有名称,是于名称空间的初衷背道而驰的


由此可见 using namespace std; 并不是可以随意使用的语句。

----update:Jun 18th , 2015 night.

觉得例子还不够丰富 就上了google看看
在Steve Donovan 《C++ by Example》中写到:
However, some people feel strongly that using namespace std cases namespace pollution because everything is dumped into the global namespace, which is what namespaces were designed to prevent. You need to understand the implications of using namespace std, and you need to recognize that there is one case where it always a bad idea.

而在国外的论坛StackOverflow
对于What requires me to declare “using namespace std;”?
Péter Török给出了这样的解释
However,
using namespace std;
is considered a bad practice because you are practically importing the whole standard namespace, thus opening up a lot of possibilities for name clashes. It is better to import only the stuff you are actually using in your code, like
using std::string;

--update: Jan. 14th, 2016 morning
原文已被删除

--update May 20th, 2016 evening
删除原文:Ubuntu Pastebin

posted on 2017-08-22 19:21  flyingwaters  阅读(193)  评论(0编辑  收藏  举报

导航