为什么是“使用命名空间标准"?被认为是不好的做法?
其他人告诉我,在代码中编写 using namespace std;
是错误的,我应该使用 std::cout
和 std::cin
直接代替.
I've been told by others that writing using namespace std;
in code is wrong, and that I should use std::cout
and std::cin
directly instead.
为什么 using namespace std;
被认为是一种不好的做法?它是效率低下还是有声明不明确变量的风险(与 std
命名空间中的函数具有相同名称的变量)?它会影响性能吗?
Why is using namespace std;
considered a bad practice? Is it inefficient or does it risk declaring ambiguous variables (variables that share the same name as a function in std
namespace)? Does it impact performance?
推荐答案
这与性能完全无关.但是考虑一下:您正在使用两个名为 Foo 和 Bar 的库:
This is not related to performance at all. But consider this: you are using two libraries called Foo and Bar:
using namespace foo;
using namespace bar;
一切正常,您可以毫无问题地从 Foo 调用 Blah()
和从 Bar 调用 Quux()
.但是有一天你升级到 Foo 2.0 的新版本,它现在提供了一个名为 Quux()
的函数.现在你遇到了一个冲突:Foo 2.0 和 Bar 都将 Quux()
导入到你的全局命名空间中.这需要一些努力来解决,尤其是在函数参数恰好匹配的情况下.
Everything works fine, and you can call Blah()
from Foo and Quux()
from Bar without problems. But one day you upgrade to a new version of Foo 2.0, which now offers a function called Quux()
. Now you've got a conflict: Both Foo 2.0 and Bar import Quux()
into your global namespace. This is going to take some effort to fix, especially if the function parameters happen to match.
如果你曾经使用过foo::Blah()
和bar::Quux()
,那么引入foo::Quux()
将是一个非事件.
If you had used foo::Blah()
and bar::Quux()
, then the introduction of foo::Quux()
would have been a non-event.
相关文章