標籤:圖片 9.png order 備忘 closed ++ cli test code
基於GCC測試:http://www.tutorialspoint.com/compile_cpp11_online.php
const A& a=fun() 與 A a= fun()
1、方法fun傳回值為 const A& 時,前者比後者 減少一次拷貝構造
1 #include <iostream> 2 3 using namespace std; 4 5 class A 6 { 7 8 public: 9 10 A() { 11 cout << "--預設建構函式--" << endl; 12 }13 14 A(const A& a) { cout << "--拷貝建構函式--" << endl; }15 16 A & operator =(const A &a)17 {18 cout << "--賦值--" << endl;19 return *this;20 }21 };22 23 class Test24 {25 public:26 const A& GetA(){ cout <<&m_a << endl; return m_a;}27 28 private:29 A m_a;30 };31 32 int main()33 {34 Test t; 35 A vec;36 cout << "------" << endl; 37 A a=t.GetA();38 cout <<&a << endl;39 cout << "------" << endl; 40 const A& b=t.GetA();41 cout <<&b << endl;42 return 0;43 }
const &
2、方法fun傳回值為 A 時,相同。只會產生一個臨時變數
A GetA(){ cout <<&m_a << endl; return m_a;}
A GetA(){ A a;cout <<&a << endl; return a;}
未實現move構造的類:A a=std::move(fun()) 與 A a=fun()
1、方法fun傳回值為 const A& 時,相同,都調用一次拷貝構造
1 class Test 2 { 3 public: 4 const A& GetA(){ cout <<&m_a << endl; return m_a;} 5 6 private: 7 A m_a; 8 }; 9 10 int main()11 {12 Test t; 13 cout << "------" << endl; 14 A a=t.GetA();15 cout <<&a << endl;16 cout << "------" << endl; 17 A b=std::move(t.GetA());18 cout <<&b << endl;19 return 0;20 }
move
2、方法fun傳回值為 A,前者比後者多一次拷貝構造
1 class Test 2 { 3 public: 4 A GetA(){ cout <<&m_a << endl; return m_a;} 5 6 private: 7 A m_a; 8 }; 9 10 int main()11 {12 Test t; 13 cout << "------" << endl; 14 A a=t.GetA();15 cout <<&a << endl;16 cout << "------" << endl; 17 A b=std::move(t.GetA());18 cout <<&b << endl;19 return 0;20 }
move
未實現move構造的類:A a;a=std::move(fun()) 與 A a;a=fun()
與fun的傳回值無關,均相同
1 class Test 2 { 3 public: 4 A GetA(){ cout <<&m_a << endl; return m_a;} 5 6 private: 7 A m_a; 8 }; 9 10 int main()11 {12 Test t; 13 cout << "------" << endl; 14 A a;15 a=t.GetA();16 cout <<&a << endl;17 cout << "------" << endl; 18 A b;19 b=std::move(t.GetA());20 cout <<&b << endl;21 return 0;22 }
賦值
1 const A& GetA(){ cout <<&m_a << endl; return m_a;}
const A&
C++編譯最佳化備忘