码迷,mamicode.com
首页 > 编程语言 > 详细

C++编译优化备忘

时间:2018-07-03 23:53:31      阅读:236      评论:0      收藏:0      [点我收藏+]

标签:图片   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 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&

技术分享图片

 

C++编译优化备忘

标签:图片   9.png   order   备忘   closed   ++   cli   test   code   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!