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?
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?
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.