Why you should not use using namespace std

People don't like typing std:: over and over, and they discover that using namespace std lets the compiler see any std name, even if unqualified. The fly in that ointment is that it lets the compiler see any std name, even the ones you didn't think about. In other words, it can create name conflicts and ambiguities.

For example, suppose your code is counting things and you happen to use a variable or function named count. But the std library also uses the name count [it's one of the std algorithms], which could cause ambiguities.

Look, the whole point of namespaces is to prevent namespace collisions between two independently developed piles of code. The using-directive [that's the technical name for using namespace XYZ] effectively dumps one namespace into another, which can subvert that goal. The using-directive exists for legacy C++ code and to ease the transition to namespaces, but you probably shouldn't use it on a regular basis, at least not in your new C++ code.

If you really want to avoid typing std::, then you can either use something else called a using-declaration, or get over it and just type std:: [the un-solution]:

  • Use a using-declaration, which brings in specific, selected names. For example, to allow your code to use the name cout without a std:: qualifier, you could insert using std::cout into your code. This is unlikely to cause confusion or ambiguity because the names you bring in are explicit.
    #include 
    #include 
    
    void f[const std::vector& v]
    {
      using std::cout;  // ← a using-declaration that lets you use cout without qualification
    
      cout 

Chủ Đề