在下面的构造函数和等号重载中,分别使用了左值的方式和右值的方式
可以看到,右值的方式相比左值,少了拷贝操作,性能更优
源代码
#include "pch.h"
#include<iostream>
#include <stdio.h>
using namespace std;
int cnt = 0;
class myc
{
int id=0;//对象id,只在构造时自增
char* str;//没有实际内容,只用来分配空间和展示地址
size_t s;//内存大小
public:
void show()
{
cout << " id: " << id << endl;
cout <<" address: " << &str << endl;
cout << " size_t: " << s << endl;
cout << "--------------------------------------------------" << endl;
}
myc(size_t x)
{
id = ++cnt;
cout << " 构造:" << id<<endl;
str = new char[x];
s = x;
}
~myc()
{
cout << " 析构:" <<id<< endl;
if (str != nullptr)
{
delete[] str;
str = nullptr;
}
s = 0;
}
myc(const myc& tmp)
{
id = ++cnt;
cout << " 拷贝构造:" << tmp.id<<" copy to " << id << endl;
s = tmp.s;
str = new char[s];
memcpy(str, tmp.str, tmp.s *sizeof(char));
}
myc(myc&& tmp)
{
id = ++cnt;
cout << " 移动构造:" <<tmp.id<<" move to "<<id << endl;
s = tmp.s;
str = tmp.str;
tmp.str = nullptr;
tmp.s = 0;
}
myc& operator=(myc& tmp)
{
cout << " copy left " <<tmp.id<<" to "<<id << endl;
if (str != nullptr && this != &tmp)
{
delete[] str;
}
s = tmp.s;
str = new char[s];
memcpy(str, tmp.str, tmp.s * sizeof(char));
return *this;
}
myc& operator=(myc&& tmp)
{
cout << " copy right " <<tmp.id<<" to " << id << endl;
if (str != nullptr && this != &tmp)
{
delete[] str;
}
str = tmp.str;
s = tmp.s;
tmp.str = nullptr;
tmp.s = 0;
return *this;
}
};
myc getTmp(size_t ll)
{
return ll > 0 ? myc(ll) : myc(100);
}
int main()
{
cout << "操作 a:" << endl;
myc a(10);
cout << "show a:" << endl;
a.show();
cout << "操作 b:" << endl;
myc b(a);
cout << "show b:" << endl;
b.show();
cout << "操作 c:" << endl;
myc c(5);
cout << "show c:" << endl;
c.show();
//这里是拷贝赋值操作
cout << "操作 c=a:" << endl;
c = a;
cout << "show c:" << endl;
c.show();
//这里是搬运赋值操作,右值引用
//为b赋了getTmp返回的临时变量(右值)
cout << "操作 b=getTmp(100):" << endl;
//这里会有两次析构是因为重载的=中包含一次删除操作,这会触发析构函数
b = getTmp(100);
cout << "show b:" << endl;
b.show();
cout << "操作 myc d=getTmp(20):" << endl;
myc d = getTmp(20);
cout << "show d:" << endl;
d.show();
cout << "end" << endl;
return 0;
}
}
运行结果