拷贝构造函数 和 移动构造函数 深拷贝
采用了深拷贝的方式,obj2 和 obj3 的 data 成员变量指向不同的内存空间,因此可以独立地释放资源而不会出现重复释放的问题.
class MyClass {
public:
int* data;
int size;
// 默认构造函数
MyClass() : data(nullptr), size(0) {}
// 拷贝构造函数(深拷贝)
MyClass(const MyClass& other) : size(other.size) {
if (other.data != nullptr) {
data = new int[size];
for (int i = 0; i < size; i++) {
data[i] = other.data[i];
}
}
else {
data = nullptr;
}
}
// 移动构造函数(深拷贝)
MyClass(MyClass&& other) noexcept : data(other.data), size(other.size) {
other.data = nullptr; // 将原始对象的指针置为空,避免悬挂指针
other.size = 0;
}
// 析构函数
~MyClass() {
delete[] data;
}
};
int main()
{
// 创建对象1
MyClass obj1;
obj1.size = 5;
obj1.data = new int[obj1.size];
for (int i = 0; i < obj1.size; i++) {
obj1.data[i] = i;
}
// 使用拷贝构造函数创建对象2
MyClass obj2 = obj1;
// 使用移动构造函数创建对象3
MyClass obj3 = std::move(obj1);
// 输出对象2和对象3的data值
std::cout << "obj2.data: ";
for (int i = 0; i < obj2.size; i++) {
std::cout << obj2.data[i] << " ";
}
std::cout << std::endl;
std::cout << "obj3.data: ";
for (int i = 0; i < obj3.size; i++) {
std::cout << obj3.data[i] << " ";
}
std::cout << std::endl;
// 释放资源
delete[] obj2.data;
delete[] obj3.data;
return 0;
}