总结:右值引用与移动语义结合,减少无必要资源的开辟来提高代码的运行效率
#include <iostream>
using namespace std;
class student
{
public:
int *age,sum;
student(){}
student(int a,int b)
{
age=new int (a);
sum=b;
cout<<"有参构造函数!"<<endl;
}
// student(student &stu)
// {
// sum=stu.sum;
// age=new int (*stu.age);
// cout<<"拷贝构造函数!"<<endl;
// }
//移动构造函数
student(student &&stu) //参数为右值引用的移动构造函数,减少拷贝构造函数中内存分配,提高效率。
{
sum=stu.sum;
age=move(stu.age);
cout<<"移动构造函数!"<<endl;
}
~student(){
if(age)
delete age;
}
};
void test1(){
student stu1(12,20);
cout<<*stu1.age<<" "<<stu1.sum<<endl;
student stu2(move(stu1));//调用参数为右值引用的移动构造函数
cout<<*stu2.age <<" "<<stu2.sum<<endl;
}
int main()
{
test1();
return 0;
}
//运行结果:
有参构造函数!
12 20
移动构造函数!
12 20