1. 程式人生 > >using namespace std;的註意事項

using namespace std;的註意事項

sin it is you 名稱 plus 有助於 多個 例如 目的

作者: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

using namespace std;的註意事項