#include <iostream>
#include <mutex>
using namespace std;
class Test
{
public:
Test()
{
if (!a)
a = new int(5);
cout << "构造函数" << endl;
}
~Test()
{
if (a)
{
delete a;
a = nullptr;
}
cout << "析构函数" << endl;
}
Test(const Test& t)
{
this->a = new int(5);
if (t.a)
*(this->a) = *(t.a);
cout << "复制构造函数" << endl;
}
Test(Test&& t)
{
if (t.a)
{
this->a = t.a;
t.a = nullptr;
}
cout << "转移构造函数" << endl;
}
Test& operator=(const Test& t)
{
this->a = new int(5);
if (t.a)
*(this->a) = *(t.a);
cout << "赋值运算符" << endl;
return *this;
}
Test& operator=(Test&& t)
{
if (t.a)
{
this->a = t.a;
t.a = nullptr;
}
cout << "转移赋值运算符" << endl;
return *this;
}
public:
int *a;
};
int main()
{
Test a;
*(a.a) = 10;
Test b;
b = a;
cout << "b" << *(b.a) << endl;
Test c(a);
cout << "c" << *(c.a) << endl;
cout << "*********************" << endl;
Test d(std::move(a));
cout << "d" << *(d.a) << endl;
Test e;
e = std::move(a);
cout << "e" << *(e.a) << endl;
system("pause");
return 0;
}
C++随手笔记(十四) 空类中的默认函数,转移构造函数、转移赋值操作符、类中有指针
于 2022-09-16 22:30:13 首次发布
这段代码展示了C++中类的构造函数、复制构造函数、转移构造函数以及赋值运算符和转移赋值运算符的实现。在main函数中,创建并操作了多个Test类的对象,演示了对象间的复制和资源管理。
1356

被折叠的 条评论
为什么被折叠?



