<分区>
使用 using 声明的两种方式是
using std::string;
using std::vector;
或
using namespace std;
哪种方式更好?
<分区>
使用 using 声明的两种方式是
using std::string;
using std::vector;
或
using namespace std;
哪种方式更好?
最佳答案
视情况而定。
如果您想将单个名称注入(inject)另一个范围,使用声明会更好,例如
namespace foolib
{
// allow vector to be used unqualified within foo,
// or used as foo::vector
using std::vector;
vector<int> vec();
template<typename T> struct Bar { T t; };
template<typename T>
void swap(Bar<T>& lhs, Bar<T>& rhs)
{
using std::swap;
// find swap by ADL, otherwise use std::swap
swap(lhs.t, rhs.t);
}
}
但有时您只需要所有名称,这就是 using 指令的作用。这可以在函数中局部使用,也可以在源文件中全局使用。
将 using namespace
放在函数体之外应该只在您确切知道包含什么的地方进行,这样它是安全的(即不在标题中,您不知道在该 header 之前或之后将包含什么)尽管许多人仍然不赞成这种用法(有关详细信息,请阅读 Why is "using namespace std" considered bad practice? 中的答案):
#include <vector>
#include <iostream>
#include "foolib.h"
using namespace foo; // only AFTER all headers
Bar<int> b;
使用 using 指令的一个很好的理由是命名空间只包含少量有意隔离的名称,并且设计为由 using 指令使用:
#include <string>
// make user-defined literals usable without qualification,
// without bringing in everything else in namespace std.
using namespace std::string_literals;
auto s = "Hello, world!"s;
因此,没有单一的答案可以说一个普遍优于另一个,它们有不同的用途,并且在不同的情况下每个都更好。
关于 using namespace
的首次使用,C++ 的创建者 Bjarne Stroustrup 在 The C++ Programming Language, 4th Ed 的§14.2.3 中有这样的说法(强调我的):
Often we like to use every name from a namespace without qualification. That can be achieved by providing a
using
-declaration for each name from the namespace, but that's tedious and requires extra work each time a new name is added to or removed from the namespace. Alternatively, we can use ausing
-directive to request that every name from a namespace be accessible in our scope without qualification. [...]
[...] Using ausing
-directive to make names from a frequently used and well-known library available without qualification is a popular technique for simplifying code. This is the technique used to access standard-library facilities throughout this book. [...]
Within a function, ausing
-directive can be safely used as a notational convenience, but care should be taken with globalusing
-directives because overuse can lead to exactly the name clashes that namespaces were introduced to avoid. [...]
Consequently, we must be careful withusing
-directives in the global scope. In particular, don't place ausing
-directive in the global scope in a header file except in very specialized circumstances (e.g. to aid transition) because you never know where a header might be#include
d.
对我来说,这似乎比坚持认为它不好且不应使用要好得多。
关于c++ - 使用 std::<type> 与使用 std 命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31450129/