c++ - 内联函数实际上做了什么?

标签 c++ c

<分区>

我在网上搜索了一些与内联函数相关的主题,但没有一个能解决我的疑问。

到目前为止,我知道内联函数与方法或 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 关键字用于强制编译器将代码粘贴到调用函数的位置。该技术用于消除函数调用开销。那是编译器在优化方面不太聪明的时代。

关于c++ - 内联函数实际上做了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27891113/

相关文章:

c++ - 命令提示符关闭而不接受输入

c++ - 就地 Cholesky 逆

c++ - 解析 C/C++ 源代码 : How are token boundaries/interactions specified in lex/yacc?

c++ - 寻找与另一个相反的 vector ?

c - 学习如何在 C 中解析字符串和使用结构

c - 取消引用 void 指针

c++ - switch 语句 C++ 和 glut

c++ - 无法从 C++ 中的 vector 中删除 void 指针

c - 段错误(在kali中使用gcc)

c++ - 这个用于计数的链表有什么问题