33

(Not) using namespace std;

 5 years ago
source link: https://www.tuicool.com/articles/hit/ENBv6r7
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
using namespace std;

This is called a using directive . Using it in code that is supposed to work for years is not a good idea.

Sometimes programmers are given advice to just type using namespace std; and all things from the Standard Library can be used easily, without bothering with namespaces. This is a good advice when you are learning C++ and when you are doing toy examples, or write small private programs. Because for these programs it is not a big deal if they cease to compile once you change the compiler or language version.

using namespace std; makes every symbol declared in namespace std accessible from the global namespace, without namespace qualifiers. You do not know how many names this is, and what those names are. If you upgrade to the newer version of C++, with a bigger Standard Library, you will get even more names “injected” into global namespace: perhaps names that you have already declared yourself in your program.

Suppose you are compiling programs in C++14. Suppose, you are using using namespace std; . At some point you define your type, in the global namespace, called byte . It doesn’t have to be a type: it can be a function. It doesn’t have to be declared in the global namespace: you could declare it in my_namespace and then just do using namespace my_namespace; . And you can use your neat type easily and correctly in your program:

#include <string>
using namespace std;

class byte {};

int main()
{
  byte b;
  // ...
}

Now, after a long anticipation, you migrate your program to C++17. You might not know that C++17 defines enum class byte in namespace std . Maybe you did not expect it in header <string> . But suddenly, name byte becomes ambiguous: you have two of them accessible in the global namespace. If this suddenly happens in many files in a big project, fixing this might become a problem.

This is because using namespace std; means not only “inject all names declared in std even though I do not know all of them”, but also, “whatever names are added to std in the future, even if they clash with my definitions, keep injecting them also”.

As an alternative to using namespace std; , it is recommended to either prefix every use of the Standard Library components with std:: or use a using declaration (as opposed to using directive) to only select these names that you intend to use:

#include <string>
using std::string;

This advice, in fact, applies to any namespace that you are not in control of: not only std .

Advertisements


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK