#include <iostream>
using namespace std;
class temp
{
private:
char *a ;
public:
temp(char c, char b)
{
a = new char[2];
a[0] = c;
a[1] = b;
cout << "构造" << endl;
}
temp(temp &t):a(t.a)
{
a = new char[2];
cout << "拷贝" << endl;
}
temp(temp &&t):a(t.a)
{
t.a = NULL;
cout << "移动" << endl;
}
void show(void)
{
//cout << this->a[0] << endl;
printf("%d\r\n", this->a[0]);
}
~temp() { cout << "析构" << endl; delete[] a; }
};
temp get(void)
{
temp d(3, 4);
cout << "666" << endl;
return d;
}
int main(void)
{
temp c(1, 2);//构造
temp b = c;//拷贝
//temp b = move(c);//左值强制转化为右值,将拷贝改进为移动
c.show();
temp d = get();//移动
system("pause");
return 0;
}
拷贝、移动构造
最新推荐文章于 2024-09-16 17:46:36 发布
该篇博客探讨了C++中的类实例化过程,包括构造函数、拷贝构造函数和移动构造函数的使用。通过示例代码展示了如何初始化对象,以及在对象传递和返回时,如何利用拷贝和移动构造函数优化性能。同时还涉及了对象生命周期中的析构函数。
摘要由CSDN通过智能技术生成