C++編譯優(yōu)化備忘
基于GCC測試:http://www.tutorialspoint.com/compile_cpp11_online.php
const A& a=fun() 與 A a= fun()
1、方法fun返回值為 const A& 時(shí),前者比后者 減少一次拷貝構(gòu)造
1 #include <iostream> 2 3 using namespace std; 4 5 class A 6 { 7 8 public: 9 10 A() { 11 cout << "--默認(rèn)構(gòu)造函數(shù)--" << endl; 12 } 13 14 A(const A& a) { cout << "--拷貝構(gòu)造函數(shù)--" << endl; } 15 16 A & operator =(const A &a) 17 { 18 cout << "--賦值--" << endl; 19 return *this; 20 } 21 }; 22 23 class Test 24 { 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 }

2、方法fun返回值為 A 時(shí),相同。只會生成一個(gè)臨時(shí)變量
A GetA(){ cout <<&m_a << endl; return m_a;}

A GetA(){ A a;cout <<&a << endl; return a;}

未實(shí)現(xiàn)move構(gòu)造的類:A a=std::move(fun()) 與 A a=fun()
1、方法fun返回值為 const A& 時(shí),相同,都調(diào)用一次拷貝構(gòu)造
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 }

2、方法fun返回值為 A,前者比后者多一次拷貝構(gòu)造
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 }

未實(shí)現(xiàn)move構(gòu)造的類:A a;a=std::move(fun()) 與 A a;a=fun()
與fun的返回值無關(guān),均相同
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;}

每多學(xué)一點(diǎn)知識,就少寫一行代碼
浙公網(wǎng)安備 33010602011771號