Warm tip: This article is reproduced from serverfault.com, please click

Why is "using namespace std;" considered bad practice?

发布于 2009-09-21 03:08:23

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.

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?

Questioner
akbiggs
Viewed
0
28k 2019-09-20 06:23:42

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;

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.

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