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?
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.
I've always liked Python's "import big_honkin_name as bhn" so you can then just use "bhn.something" rather than "big_honkin_name.something"- really cuts down on the typing. Does C++ have something like that?
@Pax namespace io = boost::filesystem;
I think it's overstating things to say it's "some effort to fix". You'll have no instances of the new foo::Quux so just disambiguate all your current uses with bar::Quux.
Would any sensible person create a library with types whose unqualified name collide with the std types?
@TomA: The problem with
#define
is that it doesn't restrict itself to namespaces, but tramples over the whole code base. A namespace alias is what you want.