C++ 中的内联函数

Suraj P 2023年10月12日
  1. 为什么在 C++ 中使用 inline 函数
  2. 在 C++ 中实现内联函数
  3. 在 C++ 中将 constructordestructor 实现为 inline 函数
  4. 在 C++ 中实现 inline 函数的优缺点
C++ 中的内联函数

本文将讨论 C++ 中的 inline 函数、如何实现它们以及使用它们的优缺点。

为什么在 C++ 中使用 inline 函数

每当我们执行程序时,CPU 都会在函数调用之后存储指令的内存地址;它将参数复制到堆栈上并将控制权转移到指定的函数。

然后 CPU 执行代码,返回特定内存位置的值,并再次返回到被调用的函数。如果大部分时间都花在切换而不是执行功能上,它可能会产生额外的开销。

这种开销在执行复杂的 CPU 密集型任务的大型函数中是微不足道的,因为大部分时间只花在执行上。

但是,当我们有许多只执行基本任务的小功能时,这种开销会变得很大。大部分时间都花在切换上,几乎没有时间花在执行上。

因此,当我们有许多小功能以节省切换时间并提高效率时,内联的概念会很方便。

每当在编译时在代码中将任何函数声明为内联时,它不会在函数调用时分配地址,而是复制整个函数代码并将其放在该位置。

语法:

inline return_type function_name(arguments)
{
...
}

inline 函数只是对编译器的请求,因此编译器可以在以下情况下忽略它:

  1. 函数有静态变量;
  2. 函数有 gotoswitch 语句;
  3. 函数是递归的;
  4. 函数有循环。

inline 的概念通常与类一起使用。

在 C++ 中实现内联函数

示例代码:

#include <iostream>
using namespace std;

class myClass {
  int a, b;

 public:
  void sum();
};

inline void myClass::sum() {
  cout << "Enter first value:";
  cin >> a;
  cout << "Enter second value:";
  cin >> b;
  cout << "Sum of two numbers is " << a + b << endl;
}

int main() {
  cout << "Program using inline function\n";
  myClass obj;
  obj.sum();
}

在上面的代码中,我们在定义函数时将函数声明为内联,因为在类外部而不是在类内部编写实际的内联函数定义是一种很好的编程习惯。

然而,一个类中的函数定义默认是一个 inline 函数定义,即使没有使用 inline 关键字。

输出:

Program using inline function
Enter first value:12
Enter second value:13
Sum of two numbers is 25

在 C++ 中将 constructordestructor 实现为 inline 函数

使用上面的例子并在定义类的同时在类之外制作 inline 函数,我们甚至可以将 constructordestructor 制作为 inline

示例代码:

#include <iostream>
using namespace std;

class myClass {
  int a, b;

 public:
  myClass();
  ~myClass();
  void sum();
};

inline myClass::myClass() {
  a = 100;
  b = 200;
}

inline myClass::~myClass() { cout << "destroying the object\n"; }

inline void myClass::sum() {
  cout << "Sum of two numbers is " << a + b << endl;
}

int main() {
  cout << "Program using inline function\n";
  myClass obj;
  obj.sum();
}

输出:

Program using inline function
Sum of two numbers is 300
destroying the object

在 C++ 中实现 inline 函数的优缺点

现在,让我们看看实现 inline 函数的一些优点:

  1. 减少函数调用的开销。
  2. 它节省了函数返回调用的开销。
  3. 节省入栈和出栈变量的开销。

虽然有用,但它也有一些缺点:

  1. 如果我们使用过多的 inline 函数,二进制可执行文件的大小可能会变大,因为这里会发生相同代码的重复。
  2. 内联函数过多会降低指令的缓存命中率,从而影响指令从缓存内存到主内存的速度。
  3. 在代码大小比速度更重要的嵌入式系统中,内联函数将无济于事。
  4. 可能会出现抖动,这会降低计算机的内存性能。
作者: Suraj P
Suraj P avatar Suraj P avatar

A technophile and a Big Data developer by passion. Loves developing advance C++ and Java applications in free time works as SME at Chegg where I help students with there doubts and assignments in the field of Computer Science.

LinkedIn GitHub

相关文章 - C++ Function