This is a modified version of another answer I wrote on the same subject. Up to version 3 now.
The major issue is name conflicts, in that if you have a variable called count
in your code and you are using namespace std;
it will be ambiguous as to what you mean. It isn't just count
. reverse
and equal
will also be included, which are all common identifiers. For example, this will result in a compile error:
#include <algorithm>
using namespace std;
int count;
int main(int argc, char* argv[]){
count = 1;
}
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 without having to check the top of the file every other line to see if you mean std::string
or mylib::string
when you write string
It is also worth noting that you should never put a using namspace xyz
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.
(From Effective C++) In the majority of cases it is very beneficial to use
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
overstd::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.