Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
505 views
in Technique[技术] by (71.8m points)

c++ - 为什么“使用命名空间标准”被认为是不好的做法?(Why is “using namespace std;” considered bad practice?)

I've been told by others that writing using namespace std;

(其他人告诉我, using namespace std;编写using namespace std;)

in code is wrong, and that I should use std::cout and std::cin directly instead.

(在代码中是错误的,我应该直接使用std::coutstd::cin代替。)

Why is using namespace std;

(为什么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)?

(是效率低下还是冒着声明模棱两可的变量(与std名称空间中的函数具有相同名称的变量)的风险?)

Does it impact performance?

(它会影响性能吗?)

  ask by akbiggs translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is not related to performance at all.

(这根本与性能无关。)

But consider this: you are using two libraries called Foo and Bar:

(但是考虑一下:您正在使用两个名为Foo和Bar的库:)

using namespace foo;
using namespace bar;

Everything works fine, and you can call Blah() from Foo and Quux() from Bar without problems.

(一切正常,您可以从Foo调用Blah()并从Bar调用Quux()而不出现问题。)

But one day you upgrade to a new version of Foo 2.0, which now offers a function called Quux() .

(但是有一天,您将升级到Foo 2.0的新版本,该版本现在提供了称为Quux()的功能。)

Now you've got a conflict: Both Foo 2.0 and Bar import Quux() into your global namespace.

(现在您有一个冲突:Foo 2.0和Bar都将Quux()导入到全局名称空间中。)

This is going to take some effort to fix, especially if the function parameters happen to match.

(这将需要花费一些时间来解决,特别是在功能参数碰巧匹配的情况下。)

If you had used foo::Blah() and bar::Quux() , then the introduction of foo::Quux() would have been a non-event.

(如果您使用过foo::Blah()bar::Quux() ,那么foo::Quux()的引入将是非事件。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...