为什么尽量不要使用using namespace std?

作者:MacTvish
链接:http://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;效果会更好


举个血淋淋的例子
在NOIP2014提高组比赛时 有个朋友因为用到了计数器 就用了count (全局声明using namespace std;)
本地编译(Dev-C++)通过 测试一切正常
但在提交答案之后 走出考场 谈论比赛过程时无意中提到count
我很惊讶 为何能编译通过 我以前在学校训练时用的C-free声明using namespace std;时用count会报错指出冲突
所以从那时候开始我在做题时就没有用过using编译指令 只用using声明
他一拍脑袋说忘了这个茬了但是后悔已经晚了
他那题由于编译未通过 0分只拿到了省三


----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;
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值