默认的六个构造
#include <iostream>
using namespace std;
//系统默认提供的构造
#include <iostream>
using namespace std;
class A {
public:
// 构造函数,接受一个整数参数,默认为0
A(int i = 0) {
_i = new int; // 动态分配内存
*_i = i; // 将传入的值赋给动态分配的内存
cout << "A()" << endl;
}
// 析构函数
~A() {
if (_i != nullptr) { // 检查指针是否为空
delete _i; // 释放动态分配的内存
}
cout << "~A()" << endl;
}
// 拷贝构造函数
A(const A &another) {
_i = new int; // 动态分配新的内存
*_i = *another._i; // 将另一个对象的值拷贝到新分配的内存中
cout << "A(const A &another)拷贝构造函数" << endl;
}
// 移动构造函数
A(A &&another) {
_i = another._i; // 将另一个对象的指针直接赋值给当前对象
another._i = nullptr; // 将另一个对象的指针置为空,防止重复释放
cout << "A(A &&another)移动构造函数" << endl;
}
// 赋值拷贝运算符
A &operator=(const A &another) {
if (this != &another) { // 检查是否是自我赋值
delete _i; // 释放当前对象的内存
_i = new int; // 动态分配新的内存
*_i = *another._i; // 将另一个对象的值拷贝到新分配的内存中
}
cout << "A &operator=(const A &another)赋值拷贝运算符" << endl;
return *this; // 返回当前对象的引用
}
// 移动赋值运算符
A &operator=(A &&another) {
if (this != &another) { // 检查是否是自我赋值
delete _i; // 释放当前对象的内存
_i = another._i; // 将另一个对象的指针直接赋值给当前对象
another._i = nullptr; // 将另一个对象的指针置为空,防止重复释放
}
cout << " A &operator=(A &&another) 移动赋值运算符" << endl;
return *this; // 返回当前对象的引用
}
protected:
int *_i; // 指向动态分配内存的指针
};
int main() {
A a;
A b(a);//A(const A &another)拷贝构造函数
A c(std::move(a));//A(A &&another)移动构造函数
//此时a已经null
A d = c; //A(const A &another)拷贝构造函数
A e =std::move(d);//A(A &&another)移动构造函数
A f;
f=std::move(e); //A &operator=(A &&another) 移动赋值运算符
//此时e已经null
return 0;
}