我正在尝试使用内联函数进行实验。我认为函数体的替换是在预处理时执行的。但事实并非如此。如果我们将内联函数声明为以下
//--main.cpp--//
....
inline void bar();
....
然后运行 g++ -E main.cpp 然后我们可以看到内联函数没有变化。那么替换体函数什么时候执行呢?
最佳答案
函数内联是一个编译时操作。注意,内联不是命令,而是对编译器的请求,编译器可以随意忽略它。例如,大型方法、递归方法、包含循环的方法或其他方法调用通常不是内联的。当编译器执行内联时,它会用方法体代替方法调用,有点类似于宏扩展,但这个过程更复杂。与宏不同,编译器不会盲目地替换方法调用,它必须照顾方法的参数。
按照标准
A function declaration (8.3.5, 9.3, 11.4) with an inline specifier declares an inline function. The
inline specifier indicates to the implementation that inline substitution of the function body at the
point of call is to be preferred to the usual function call mechanism. An implementation is not required
to perform this inline substitution at the point of call;
关于c++ - 内联函数体的替换何时执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23605784/