c++移动构造

  下面随笔给出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...

 

posted @ 2021-02-25 15:44  `Konoha  阅读(637)  评论(0编辑  收藏  举报