#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;
}
由上方測試可知:
- 對于内聯函數,C++有可能直接用函數體代碼來替代對函數的調用,這一過程稱為函數體的内聯展開。
- 對于隻有幾條語句的小函數來說,與函數的調用、傳回有關的準備和收尾工作的代碼往往比函數體本身的代碼要大得多。是以,對于這類簡單的、使用頻繁的小函數,将之說明為内聯函數可提高運作效率。
- 内聯函數是直接複制“鑲嵌”到主函數中去的,就是将内聯函數的代碼直接放在内聯函數的位置上,這與一般函數不同,主函數在調用一般函數的時候,是指令跳轉到被調用函數的入口位址,執行完被調用函數後,指令再跳轉回主函數上繼續執行後面的代碼;而由于内聯函數是将函數的代碼直接放在了函數的位置上,是以沒有指令跳轉,指令按順序執行。
- 内聯函數作用域仍舊在函數體内。