C++中inline内联函数

内联函数(inline function与一般的函数不同,不是在调用时发生控制转移而是在编译阶段将函数体嵌入到每一个调用语句中


内联函数(inline function)与编译器的工作息息相关。编译器会将程序中出现内联函数的调用表达式用内联函数的函数体来替换。


Cpp代码  

  1. /** 
  2. *在类里定义的成员函数会被隐含指定为内置函数 
  3. */  
  4.   
  5. #include "stdafx.h"  
  6. #include <iostream>  
  7. #include <string>  
  8.   
  9. using namespace std;  
  10.   
  11. class CStudent  
  12. {  
  13. public:  
  14.     void display()  
  15.     {  
  16.         cout<<"name:"<<name<<endl;  
  17.     }  
  18.     string name;  
  19. };  
  20.   
  21. int main(int argc, char* argv[])  
  22. {  
  23.     CStudent myStudent;  
  24.     myStudent.name="Erin";  
  25.     myStudent.display();  
  26.     return 0;  
  27. }  

 

Cpp代码  

  1. /** 
  2. *类外定义的函数用inline指定为内置函数 
  3. */  
  4.   
  5. #include "stdafx.h"  
  6. #include <iostream>  
  7. #include <string>  
  8.   
  9. using namespace std;  
  10.   
  11. class CStudent  
  12. {  
  13. public:  
  14.     inline void display();  
  15.     string name;  
  16. };  
  17.   
  18. inline void CStudent::display()  
  19. {  
  20.     cout<<"name:"<<name<<endl;  
  21. }  
  22.   
  23. int main(int argc, char* argv[])  
  24. {  
  25.     CStudent myStudent;  
  26.     myStudent.name="Erin";  
  27.     myStudent.display();  
  28.     return 0;  
  29. }  

 

Cpp代码  

  1. /** 
  2. *无内置函数 
  3. *既没有在类内定义函数,也没有用inline在类外定义函数 
  4. */  
  5.   
  6. #include "stdafx.h"  
  7. #include <iostream>  
  8. #include <string>  
  9.   
  10. using namespace std;  
  11.   
  12. class CStudent  
  13. {  
  14. public:  
  15.     void display();  
  16.     string name;  
  17. };  
  18.   
  19. void CStudent::display()  
  20. {  
  21.     cout<<"name:"<<name<<endl;  
  22. }  
  23.   
  24. int main(int argc, char* argv[])  
  25. {  
  26.     CStudent myStudent;  
  27.     myStudent.name="Erin";  
  28.     myStudent.display();  
  29.     return 0;  
  30. }  

 


内联函数的优点:

     首先来看函数调用的实质,其实是将程序执行转移到被调用函数所存放的内存地址,将函数执行完后,在返回到执行此函数前的地方。这种转移操作需要保护现场(包括各种函数的参数的进栈操作),在被调用函数代码执行完后,再恢复现场。但是保护现场和恢复现场需要较大的资源开销。

     特别是对于一些较小的调用函数来说(如上边代码中的display()函数),若是频繁调用,函数调用过程甚至可能比函数执行过程需要的系统资源更多。所以引入内联函数,可以让程序执行效率更高。


内联函数的缺点:

      如果调用内联函数的地方过多,也可能造成代码膨胀。毕竟,编译器会把内联函数的函数体嵌入到每一个调用了它的地方,重复地嵌入。


即使在类定义中声明的成员函数可以定义在类定义的外部(并通过二元作用域分辨符“绑定”到该类),这样的成员函数仍在该类的作用域之内;也就是说,只有该类中的其他成员直到它的名称,否则就必须通过该类的对象、该类对象的引用、该类对象的指针或者二元作用域分辨运算符进行引用。

   如果成员函数定义在类定义的体内,C++编译器将尝试内联调用该成员函数。定义在类定义之外的成员函数则可以通过显式的使用关键字inline指定为内联函数。编译器不会调用任何内联函数。


你可能感兴趣的:(C++中inline内联函数)