下面隨筆給出c++移動構造,
在現實中有很多這樣的例子,我們將錢從一個賬號轉移到另一個賬號,將手機SIM卡轉移到另一臺手機,將檔案從一個位置剪切到另一個位置……移動構造可以減少不必要的復制,帶來性能上的提升,
-
C++11標準中提供了一種新的構造方法——移動構造,
-
C++11之前,如果要將源物件的狀態轉移到目標物件只能通過復制,在某些情況下,我們沒有必要復制物件——只需要移動它們,
-
C++11引入移動語意:
-
源物件資源的控制權全部交給目標物件
-
-
移動建構式
問題與解決
-
當臨時物件在被復制后,就不再被利用了,我們完全可以把臨時物件的資源直接移動,這樣就避免了多余的復制操作,
移動構造
-
什么時候該觸發移動構造?
-
有可被利用的臨時物件
-
-
移動建構式:
class_name ( class_name && )
1 //例:函式回傳含有指標成員的物件(版本1) 2 3 //使用深層復制建構式 4 5 //回傳時構造臨時物件,動態分配將臨時物件回傳到主調函式,然后洗掉臨時物件, 6 7 #include<iostream> 8 9 using namespace std; 10 11 class IntNum { 12 13 public: 14 15 IntNum(int x = 0) : xptr(new int(x)){ //建構式 16 17 cout << "Calling constructor..." << endl; 18 19 } 20 21 IntNum(const IntNum & n) : xptr(new int(*n.xptr)){//復制建構式 22 23 cout << "Calling copy constructor..." << endl; 24 25 }; 26 27 ~IntNum(){ //解構式 28 29 delete xptr; 30 31 cout << "Destructing..." << endl; 32 33 } 34 35 int getInt() { return *xptr; } 36 37 private: 38 39 int *xptr; 40 41 }; 42 43 //回傳值為IntNum類物件 44 45 IntNum getNum() { 46 47 IntNum a; 48 49 return a; 50 51 } 52 53 int main() { 54 55 cout<<getNum().getInt()<<endl; 56 57 return 0; 58 59 } 60 61 //運行結果: 62 63 Calling constructor... 64 65 Calling copy constructor... 66 67 Destructing... 68 69 0 70 71 Destructing...
1 //例:函式回傳含有指標成員的物件(版本2) 2 3 //使用移動建構式 4 5 //將要回傳的區域物件轉移到主調函式,省去了構造和洗掉臨時物件的程序, 6 7 #include<iostream> 8 9 using namespace std; 10 11 class IntNum { 12 13 public: 14 15 IntNum(int x = 0) : xptr(new int(x)){ //建構式 16 17 cout << "Calling constructor..." << endl; 18 19 } 20 21 IntNum(const IntNum & n) : xptr(new int(*n.xptr)){//復制建構式 22 23 cout << "Calling copy constructor..." << endl; 24 25 //注: 26 27 //?&&是右值參考 28 29 //?函式回傳的臨時變數是右值 30 31 } 32 33 IntNum(IntNum && n): xptr( n.xptr){ //移動建構式 34 35 n.xptr = nullptr; 36 37 cout << "Calling move constructor..." << endl; 38 39 } 40 41 ~IntNum(){ //解構式 42 43 delete xptr; 44 45 cout << "Destructing..." << endl; 46 47 } 48 49 private: 50 51 int *xptr; 52 53 }; 54 55 //回傳值為IntNum類物件 56 57 IntNum getNum() { 58 59 IntNum a; 60 61 return a; 62 63 } 64 65 int main() { 66 67 cout << getNum().getInt() << endl; return 0; 68 69 } 70 71 //運行結果: 72 73 Calling constructor... 74 75 Calling move constructor... 76 77 Destructing... 78 79 0 80 81 Destructing...
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/263623.html
標籤:C++
上一篇:c++動態記憶體分配
