天天看点

inline及指针基础

#include<iostream>
using namespace std;



void SwapWayOne(int* x, int* y){
  int temp = 0;
  temp = *x;
  *x = *y;
  *y = temp;
} 



void SwapWayTwo(int &x, int &y){  
  int temp = 0;
  temp = x;
  x = y;
  y = temp;
} 


void failedSwapWay(int x, int y){ 
  int temp = 0;
  temp = x;
  x = y;
  y = temp;
} 




inline void inlineSwapWayOne(int* x, int* y){
  
  //address of x: 0x6ffde0, address of y: 0x6ffde8
  cout << "address of x: " << &x << ", " << "address of y: " << &y << endl;
  //value of address x: 0x6ffe0c, value of address y: 0x6ffe08 
  cout << "value of address x: " << *(&x) << ", " << "value of address y: " << *(&y) << endl;
  //value of address x: 0x6ffe0c, value of address y: 0x6ffe08 
  cout << "value of address x: " << x << ", " << "value of address y: " << y << endl;
  //value of x: 5, value of y: 9 
  cout << "value of x: " << *x << ", " << "value of y: " << *y << endl;
  
  int temp = 0;
  temp = *x;
  *x = *y;
  *y = temp;
} 



inline void inlineSwapWayTwo(int &x, int &y){
  
  //address of x: 0x6ffe0c, address of y: 0x6ffe08
  cout << "address of x: " << &x << ", " << "address of y: " << &y << endl;
  //value of x: 5, value of y: 9 
  cout << "value of x: " << *(&x) << ", " << "value of y: " << *(&y) << endl;
  //value of x: 5, value of y: 9 
  cout << "value of x: " << x << ", " << "value of y: " << y << endl;
  
  int temp = 0;
  temp = x;
  x = y;
  y = temp;
} 



inline void failedSwapThoughInline(int x, int y){
  int temp = 0;
  temp = x;
  x = y;
  y = temp;
}


int main(){
  int numA = 5, numB = 9;
  cout << "Original order: " << numA << ", " << numB << endl;
  
//  failedSwapWay(numA, numB);
//  SwapWayOne(&numA, &numB);
//  SwapWayTwo(numA, numB);
//  inlineSwapWayOne(&numA, &numB);
  inlineSwapWayTwo(numA, numB);
//  failedSwapThoughInline(numA,numB); // inline function's scope is still inside!  
  
  cout << "After changed: " << numA << ", " << numB <<endl;
  
  return 0;  
}      

由上方测试可知:

  1. 对于内联函数,C++有可能直接用函数体代码来替代对函数的调用,这一过程称为函数体的内联展开。
  2. 对于只有几条语句的小函数来说,与函数的调用、返回有关的准备和收尾工作的代码往往比函数体本身的代码要大得多。因此,对于这类简单的、使用频繁的小函数,将之说明为内联函数可提高运行效率。
  3. 内联函数是直接复制“镶嵌”到主函数中去的,就是将内联函数的代码直接放在内联函数的位置上,这与一般函数不同,主函数在调用一般函数的时候,是指令跳转到被调用函数的入口地址,执行完被调用函数后,指令再跳转回主函数上继续执行后面的代码;而由于内联函数是将函数的代码直接放在了函数的位置上,所以没有指令跳转,指令按顺序执行。
  4. 内联函数作用域仍旧在函数体内。