-1

in c++ when I want to use cout to display to the console, i used to use

using namespace std;

but recently I got told to use only

using std::cout;

because it reduced overhead, what does that mean and how does it help?

wolverine
  • 1
  • 1
  • 1
    It reduces no overhead you are likely to notice. It helps out the compiler a bit by reducing the surface area that needs to be covered when searching for an identifier. The main point is `using namespace std` pulls the contents of the std namespace into the global namespace where the standard library identifiers now compete with yours. You have a function named `swap`? The standard library has dozens and a template that covers an infinite number more. Which `swap` gets called? More here: http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice – user4581301 Apr 08 '17 at 01:12
  • The main problem with `using namesace std;` is that it is a source of hard to spot bugs because namespace `std` contains so many commonly used symbols. – Galik Apr 08 '17 at 01:21

1 Answers1

1

To say it's overhead is a misnomer. There is no inherent "overhead" when using a using namespace declaration.

The reason using namespace std; is discouraged is more subtle:

Every standard header you #include has a large number of classes, functions, types, and other names declared inside a namespace std {} block. The using namespace std; declaration is essentially the same as stripping off that namespace std {} block and putting everything into the global namespace.

So, if you need to use the name cout or endl (or any of hundreds of other names) somewhere in your code where you're not referring to the standard output stream, your names will conflict with the standard names, and you'll get a pile of compiler or linker errors, or behavior that's difficult to explain.

So, you can either spend your time making sure that none of the names you're using are in the standard libraries, or you can leave it all in the std namespace, where you can unambiguously refer to it.

The standard advice is to never use the using directive in a header file, but it's fine to use it judiciously in a normal (non-header) source file.

Most coding standards and guidelines go a little further, forbidding using namespace entirely, and require you to use specific using declarations like using std::cout; where you know for certain that you aren't going to be declaring your own cout in your source file.

I prefer the latter advice, and use using std::typename; only where it makes my code substantially easier to read, and sparingly even then.

greyfade
  • 24,948
  • 7
  • 64
  • 80