c++ - 内联函数体的替换何时执行

标签 c++ inline

我正在尝试使用内联函数进行实验。我认为函数体的替换是在预处理时执行的。但事实并非如此。如果我们将内联函数声明为以下

//--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/

相关文章:

c++ - 使用内联静态数据成员有什么潜在的缺陷吗?

c++ - struct 中不可访问的模板化构造函数

android - 如何在 Android 中使用我的 OpenCV C++ 代码?

c++ - 用手指在 Canvas 上绘图。 Tizen 原生应用程序

c++ - 如何通过 C++ std::set 尽早结束迭代?

c++ - 内联与 constexpr?

c++ - 窗口最大化/最小化/恢复的 WM Windows 消息是什么?

html - 如何垂直对齐 td 内的 float 表格

css - 使用CSS在同一行显示标签和输入

css - CSS 中的 SVG DataURI 在 Firefox 中不起作用