c++ - 使用 std::<type> 与使用 std 命名空间

标签 c++ using

<分区>

使用 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 a using-directive to request that every name from a namespace be accessible in our scope without qualification. [...]
[...] Using a using-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, a using-directive can be safely used as a notational convenience, but care should be taken with global using-directives because overuse can lead to exactly the name clashes that namespaces were introduced to avoid. [...]
Consequently, we must be careful with using-directives in the global scope. In particular, don't place a using-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 #included.

对我来说,这似乎比坚持认为它不好且不应使用要好得多。

关于c++ - 使用 std::<type> 与使用 std 命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31450129/

相关文章:

c++ - 什么时候使用 using 声明?

c++ - 在循环中生成随机数_C++ 和循环中的数组 (openmp)

c++ - 序列点和评估顺序(预增量)

c++ - 使用命名空间的区别 (std::vs::std::)

namespaces - 在 Rust 中声明多个 "use"语句是否被认为是不好的风格?

c# - 异常处理(矛盾的文档/尝试最终与使用)

c++ - 如何用OpenCV模拟Matlab的medfilt2?

c++ - 为所有 Linux 发行版编译 C++

C++文件读取

c# - 使用 c# using 语句延迟实例化