This is a modified version of another answer that I wrote on the same question. Now up to version 3.
The main problem is name conflicts, 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. This is not just count . reverse and equal will also be included, which are common identifiers. For example, this will result in a compilation error:
#include <algorithm> using namespace std; int count; int main(int argc, char* argv[]){ count = 1; }
Apart from all the problems for the compiler, this is also a problem for those who start reading your code. These extra 5 characters ensure that the next person supporting your code knows exactly what you mean by not checking the top of the file for every other line to see if you have the value std::string or mylib::string when writing string
It is also worth noting that you should never put using namspace xyz in the header file, as it can spread to all files containing this header file, even if they do not want to use this namespace. Another problem is that it is also unclear that the std namespace was imported, so the maintainer (or you 3 months later) adds a variable with the same name as some obscure std function that was included in the same compilation unit and then spends an hour trying to find the cause of the compilation error.
(From Effective C ++) In most cases, it is very useful to use
using std::swap
As if there is a special version of swap, the compiler will use this, otherwise it will return to std::swap . If you call std::swap , you always use the base version, which will not call the specialized version (even if it exists).
Take, for example, the code using pimpl idiom . If the default copy can copy all the data into the actual implementation, where all that is required is a pointer replacement. Using a specialized swap can save a huge amount of runtime, and well-designed libraries should specialize it.
So,
Always prefer using std::swap over std::swap()
Avoid using namespace std in the header at all costs due to distribution, try not to use it in implementation files.
Having thousands using std::foo at the top of each file is not the way to go. In most cases, use it for common classes.
Everything else is an opinion.
Yacoby
source share