Why try not to use using namespace std?

It increases the possibility of naming conflicts.

For example, the following code:

:cat main.cc
/// @file main.cc

#include <cstdio>
#include <algorithm>
using namespace std;
int max = 0;
int main()
{
	printf("%d\n", max);
	return 0;
}

Compile error will be reported:

:g++ -O main.cc -o main
main.cc:9:17: error: reference to 'max' is ambiguous
        printf("%d\n", max);
                       ^
main.cc:6:5: note: candidate found by name lookup is 'max'
int max = 0;
    ^
/Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/algorithm:2529:1: note: candidate found by name lookup is
      'std::__1::max'
max(const _Tp& __a, const _Tp& __b)
^
/Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/algorithm:2521:1: note: candidate found by name lookup is
      'std::__1::max'
max(const _Tp& __a, const _Tp& __b, _Compare __comp)
^
1 error generated.

In general, use the command using the compiler command than using more secure, because it only introduced the name specified. If the name conflicts with the local name, the compiler will issue instructions. using the compiler command import all the names, including the name may not be required. If a conflict with the local name, the name will overwrite the local version of the name space, and the compiler does not issue a warning . In addition, open namespace name implies namespace may be scattered in multiple locations, making it difficult to know exactly what the name is added.

Steve Donovan 《C++ by Example》:

However, some people feel strongly that using namespace std cases namespace pollution because everything is dumped into the global namespace, which is what namespaces were designed to prevent. You need to understand the implications of using namespace std, and you need to recognize that there is one case where it always a bad idea.

Published 130 original articles · won praise 5 · views 20000 +

Guess you like

Origin blog.csdn.net/LU_ZHAO/article/details/104844754
Recommended