c++深拷贝
时间: 2023-07-05 09:21:50 浏览: 53
C++中的深拷贝是指在拷贝一个对象时,会创建一个新的对象,同时将原对象的所有数据成员都复制到新对象中,并且新对象和原对象的内存空间是独立的。这样,当修改新对象的数据时,原对象的数据不会受到影响。
实现深拷贝的方式是,在对象的拷贝构造函数和赋值运算符重载函数中,分别对每个数据成员进行拷贝操作。对于指针类型的成员变量,需要对其指向的内存空间进行动态分配,然后将原指针所指向的数据复制到新的内存空间中。
以下是一个示例代码:
```c++
class MyClass {
public:
MyClass() : ptr(nullptr) {}
MyClass(const MyClass& other) : ptr(nullptr) {
if (other.ptr != nullptr) {
ptr = new int(*other.ptr);
}
}
MyClass& operator=(const MyClass& other) {
if (this != &other) {
delete ptr;
ptr = nullptr;
if (other.ptr != nullptr) {
ptr = new int(*other.ptr);
}
}
return *this;
}
~MyClass() {
delete ptr;
}
private:
int* ptr;
};
```
在上述代码中,MyClass类包含一个指向int类型数据的指针ptr。在拷贝构造函数和赋值运算符重载函数中,分别对ptr进行深拷贝操作。其中,在拷贝构造函数中,需要对指针进行判空操作,以避免拷贝空指针;在赋值运算符重载函数中,需要先释放原有内存空间,再进行深拷贝操作。在析构函数中,需要释放ptr所指向的内存空间。