我曾经使用以下代码来确保包含文件不会被多次加载。
#ifndef _STRING_
#include <string>
#endif
// use std::string here
std::string str;
...
这个技巧在“API Design for C++”一书中有说明。
现在我的同事告诉我,这在 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.