我在网上搜索了一些与内联函数相关的主题,但没有一个能解决我的疑问。
到目前为止,我知道内联函数与方法或 block 的工作方式相同,但最近看到以下响应:
By declaring a function inline you tell the compiler to replace the
complete code of that function directly into the place from where it
was called. This is a rather advanced feature that requires
understanding of lower-level programming.
所以这意味着在正常功能中:我在 A 点想去 B 点,因为我离开 A 点然后去 B,对吗?
内联函数是否以这种方式工作:我在 A 点,想去 B 点,因为 B 点到达 A 点?
我上面说的对吗?
理想情况下,使用inline
关键字,编译器会将内联函数的内容粘贴到调用函数的位置。
给定:
void Print(void)
{
cout << "Hello World!\n";
}
int main(void)
{
Print();
return 0;
}
编译器会发出一条汇编指令来调用 main
函数中的 Print
函数。
当将 Print
函数声明为内联函数时,编译器将生成如下概念性的 main()
函数:
int main(void)
{
// Substitute content of Print function because it's declared as inline
cout << "Hello World!\n";
return 0;
}
请记住,inline
关键字是对编译器的建议,编译器可以忽略它。编译器可能已经内联 小函数而不使用inline
关键字。
很久以前,inline
关键字用于强制编译器将代码粘贴到调用函数的位置。该技术用于消除函数调用开销。那是编译器在优化方面不太聪明的时代。