C++编译优化备忘

基于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 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 }
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&

原文地址:https://www.cnblogs.com/loveclumsybaby/p/9260749.html