为什么尽量不要使用using namespace std?

增加了命名冲突的可能性。

例如,以下代码:

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

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

就会报编译错误:

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

一般说来,使用using命令比使用using编译命令更安全,这是由于它只导入了指定的名称。如果该名称与局部名称发生冲突,编译器将发出指示。using编译命令导入所有的名称,包括可能并不需要的名称。如果与局部名称发生冲突,则局部名称将覆盖名称空间版本,而编译器并不会发出警告。另外,名称空间的开放性意味着名称空间的名称可能分散在多个地方,这使得难以准确知道添加了哪些名称。

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.

发布了130 篇原创文章 · 获赞 5 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/LU_ZHAO/article/details/104844754