This is a modified version of another answer I wrote on the same subject. Enough of these questions and maybe I will end up with a definitive post ;)
The major issue is name conflicts, in that if you have a variable called cout in your code and you are using namespace std;
it will be ambiguous as to what you mean. It isn't just cout
. count
, reverse
and equal
will also be included, which are all common identifiers.
Disregarding all problems to the compiler, it is also a problem for anyone coming to read your code. Those extra 5 characters ensure that the next person maintaining your code knowns exactly what you mean.
It is also worth noting that you should never put
using namespace std;
In a header file, as it can propagate to all files that include that header file, even if they don't want to use that namespace. Another problem here is that it is also not clear that the std namespace has been imported, so the maintainer (or you in 3 months time) adds a variable with the same name as some obscure std function that was included into the same compilation unit and then spends an hour trying to find the cause of the compilation error.
In the majority of cases it is very beneficial to use things like
using std::swap
As if there is a specialized version of swap, the compiler will use that, otherwise it will fall back on std::swap
. If you call std::swap
, you always use the basic version, which will not call the specialized version (even if it exists).
Take for example code using the pimpl idiom. Where as the default copy may copy all the data in the actual implementation, where as all that needs doing is swapping the pointers. Using a specialized swap could save huge amounts of execution time, and well designed libraries should specialize it.
In summary,
Always prefer using std::swap
over std::swap()
Avoid using namespace std
in a header at all costs due to propagation, try to avoid using it in implementation files.
Having thousands of using std::foo
at the top of every file is not the way to go. At most use it for commonly use classes.
Everything else is opinion.