您的位置:首页 > 其它

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

2015-11-07 13:15 513 查看
作者: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(随意)
[code]


而应这样做

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 becauseeverything 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 italways 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;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: