当前位置:首页 > 通信资讯 > 正文

c++移动构造函数(c++默认移动构造)

 下面随笔给出c++移动构造。

  在现实中有很多这样的例子,我们将钱从一个账号转移到另一个账号,将手机SIM卡转移到另一台手机,将文件从一个位置剪切到另一个位置……移动构造可以减少不必要的复制,带来性能上的提升。

  • C++11标准中提供了一种新的构造方法——移动构造。
  • C++11之前,如果要将源对象的状态转移到目标对象只能通过复制。在某些情况下,我们没有必要复制对象——只需要移动它们。
  • C++11引入移动语义:

源对象资源的控制权全部交给目标对象

  • 移动构造函数

问题与解决

当临时对象在被复制后,就不再被利用了。我们完全可以把临时对象的资源直接移动,这样就避免了多余的复制操作。

c++移动构造函数(c++默认移动构造)

移动构造

  • 什么时候该触发移动构造?

有可被利用的临时对象

  • 移动构造函数:

     class_name ( class_name && )

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 //例:函数返回含有指针成员的对象(版本1) //使用深层复制构造函数 //返回时构造临时对象,动态分配将临时对象返回到主调函数,然后删除临时对象。 #include<iostream> using namespace std; class IntNum { public:   IntNum(int x = 0) : xptr(new int(x)){ //构造函数     cout << "Calling constructor..." << endl;    }   IntNum(const IntNum & n) : xptr(new int(*n.xptr)){//复制构造函数     cout << "Calling copy constructor..." << endl;   };   ~IntNum(){ //析构函数     delete xptr;     cout << "Destructing..." << endl;   }   int getInt() { return *xptr; } private:   int *xptr; }; //返回值为IntNum类对象   IntNum getNum() {     IntNum a;     return a;   } int main() {   cout<<getNum().getInt()<<endl;   return 0; } //运行结果: Calling constructor... Calling copy constructor... Destructing... 0 Destructing...
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 //例:函数返回含有指针成员的对象(版本2) //使用移动构造函数 //将要返回的局部对象转移到主调函数,省去了构造和删除临时对象的过程。 #include<iostream> using namespace std; class IntNum { public:   IntNum(int x = 0) : xptr(new int(x)){ //构造函数     cout << "Calling constructor..." << endl;   }   IntNum(const IntNum & n) : xptr(new int(*n.xptr)){//复制构造函数     cout << "Calling copy constructor..." << endl;    //注:   //•&&是右值引用   //•函数返回的临时变量是右值   }   IntNum(IntNum && n): xptr( n.xptr){ //移动构造函数     n.xptr = nullptr;     cout << "Calling move constructor..." << endl;   }   ~IntNum(){ //析构函数     delete xptr;     cout << "Destructing..." << endl;   } private:   int *xptr; }; //返回值为IntNum类对象   IntNum getNum() {   IntNum a;   return a; } int main() {   cout << getNum().getInt() << endl; return 0; } //运行结果: Calling constructor... Calling move constructor... Destructing... 0 Destructing...

以上就是c++ 移动构造相关总结的详细内容,更多关于c++ 移动构造的资料请关注服务器之家其它相关文章!

原文链接:https://www.cnblogs.com/iFrank/archive/2021/02/25/14447306.html

如果您对该产品感兴趣,请填写办理(客服微信:xiaoxiongyidong)

为您推荐:

发表评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。