为什么似乎没有必要包含一些 STL headers

Why it seems not necessary to include some STL headers

我认为需要包含一些 header 以使用 gcc(4.9) 进行编译,

#include <algorithm> // for std::transform
#include <numeric>   // for std::adjacent_difference

但是,我发现根本没有必要包含它们,我仍然可以调用 例如,以下函数

std::adjacent_difference (V1.begin(), V1.end(), V2.begin());
std::transform(V2.begin(), V2.end(), V3.begin(), V4.begin(), std::divides<double>());

也许我误解了包含 header 文件的机制...有什么提示吗?

一个 header 包含其他 header 是很典型的。 header x 包含的 header 将包含在任何包含 x 的文件中。一旦您掌握了 including 文件的另一种方式,理解起来应该是微不足道的。在这种情况下,其中一个标准 header 恰好包含在另一个标准中。

headers 包含的文件可以在版本之间更改。如果您不包含必需的 header,您的程序可能会在另一个(版本的)标准库下中断,即使它可能看起来在当前实现中工作。当然,这也适用于其他图书馆。

C++ 标准在第 17.6.5.2 节中说明如下 [res.on.headers]:

A C++ header may include other C++ headers.

对于您的问题,这意味着编译器可以像您包含其他 C++ header 一样运行。在您的示例中,如果您包含 <algorithm>,则允许​​编译器包含 <numeric> header,反之亦然。

但这还不是全部。该标准还说:

A C++ header shown in its synopsis as including other C++ headers shall provide the declarations and definitions that appear in the synopses of those other headers.

并且:

The C standard headers [...] shall include only their corresponding C++ standard header [...]

(请注意,我引用的是最新的免费 C++11 草案。ISO 标准的最终版本不是免费的。请参阅 https://isocpp.org/std/the-standard。)

<utility> header 是 C++ header 的一个例子,保证包含另一个。它的概要明确地包括<initializer_list>。这意味着符合规范的编译器 必须 接受以下内容:

#include <utility>
// #include <initializer_list> // not needed

int main()
{
    std::initializer_list<int> x = {};
}

对于 C headers,相反,这意味着以下 不能 编译:

#include <stdio.h>

int main()
{
    std::cout << "\n"; // must not compile
}

您的实施文档肯定证实了标准所说的内容。例如,documentation for Visual C++ 2013 表示:

A C++ library header includes any other C++ library headers it needs to define needed types. (Always include explicitly any C++ library headers needed in a translation unit, however, lest you guess wrong about its actual dependencies.) A Standard C header never includes another standard header.

这里给出的建议很好;不依赖于自动包含。明确包含您需要的一切。