我曾经使用以下代码来确保不多次加载包含文件。

#ifndef _STRING_
#include <string>
#endif

// use std::string here
std::string str;
...

这个技巧在“C++ API 设计”一书中有说明。

现在我的同事告诉我,这在 Visual Studio 中不是必需的,因为如果 string 的实现头文件包含 #pragma once ,则不需要包含保护来提高编译速度。

那是对的吗?

引自原书:
7.2.3 Redundant #include Guards
Another way to reduce the overhead of parsing too many include files is to add redundant preprocessor
guards at the point of inclusion. For example, if you have an include file, bigfile.h, that looks
like this
#ifndef BIGFILE_H
#define BIGFILE_H
// lots and lots of code
#endif
then you might include this file from another header by doing the following:
#ifndef BIGFILE_H
#include "bigfile.h"
#endif
This saves the cost of pointlessly opening and parsing the entire include file if you’ve already
included it.

最佳答案

通常术语“包含守卫”意味着这个 #ifdef#define#endif 序列被放在 这个文件中的特定头文件 的内容周围。

许多 C++ 编译器提供 #pragma once 语句,以保证外部的相同行为。但是为了可移植的 C/C++ 代码,我不鼓励使用它。

更新 (根据 OP 的编辑)
此外,将 #ifdef#endif 放在另一个文件中的 #include 语句周围可能会阻止预处理器打开包含文件本身(从而稍微减少编译时间和内存使用量)。我希望 #pragma once 会自动执行此操作,但不能确定(这可能是特定于实现的)。

关于c++ - Visual Studio 上是否需要 "Redundant #include Guards"?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15119273/

10-11 20:23