C++中的移动构造函数及move语句示例详解

2020-01-06 17:28:49王旭

*************************************************************

**移动构造函数的参数和拷贝构造函数不同,拷贝构造函数的参数是一个左值引用,但是移动构造函数的初值是一个右值引用。(关于右值引用大家可以看我之前的文章,或者查找其他资料)。这意味着,移动构造函数的参数是一个右值或者将亡值的引用。也就是说,只用用一个右值,或者将亡值初始化另一个对象的时候,才会调用移动构造函数。而那个move语句,就是将一个左值变成一个将亡值。

移动构造函数应用最多的地方就是STL中

给出一个代码,大家自行验证使用move和不适用move的区别吧


#include <iostream>
#include <cstring>
#include <cstdlib>
#include <vector>
using namespace std;

class Str{
 public:
 char *str;
 Str(char value[])
 {
  cout<<"普通构造函数..."<<endl;
  str = NULL;
  int len = strlen(value);
  str = (char *)malloc(len + 1);
  memset(str,0,len + 1);
  strcpy(str,value);
 }
 Str(const Str &s)
 {
  cout<<"拷贝构造函数..."<<endl;
  str = NULL;
  int len = strlen(s.str);
  str = (char *)malloc(len + 1);
  memset(str,0,len + 1);
  strcpy(str,s.str);
 }
 Str(Str &&s)
 {
  cout<<"移动构造函数..."<<endl;
  str = NULL;
  str = s.str;
  s.str = NULL;
 }
 ~Str()
 {
  cout<<"析构函数"<<endl;
  if(str != NULL)
  {
  free(str);
  str = NULL;
  }
 }
};
int main()
{
 char value[] = "I love zx";
 Str s(value);
 vector<Str> vs;
 //vs.push_back(move(s));
 vs.push_back(s);
 cout<<vs[0].str<<endl;
 if(s.str != NULL)
 cout<<s.str<<endl;
 return 0;
}

总结

以上就是这篇文章的全部内容,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对ASPKU的支持。


注:相关教程知识阅读请移步到C++教程频道。