请告诉我深拷贝的析构函数怎么写
时间: 2024-05-07 20:15:26 浏览: 13
深拷贝的析构函数需要释放堆内存,并确保不会出现内存泄漏。具体实现如下:
```c++
class MyClass {
public:
MyClass() {
// 构造函数
}
~MyClass() {
// 析构函数
if (m_ptr != nullptr) {
delete m_ptr;
m_ptr = nullptr;
}
}
MyClass(const MyClass& other) {
// 拷贝构造函数
if (other.m_ptr != nullptr) {
m_ptr = new int(*other.m_ptr);
} else {
m_ptr = nullptr;
}
}
MyClass& operator=(const MyClass& other) {
// 赋值运算符重载
if (this != &other) {
if (m_ptr != nullptr) {
delete m_ptr;
}
if (other.m_ptr != nullptr) {
m_ptr = new int(*other.m_ptr);
} else {
m_ptr = nullptr;
}
}
return *this;
}
private:
int* m_ptr;
};
```
在析构函数中,首先检查指针是否为空,如果不为空,则释放指向的内存,并将指针置为空。在拷贝构造函数和赋值运算符重载中,需要先检查源对象的指针是否为空,如果不为空,则为成员变量分配新的内存,并将源对象的值复制到新的内存中。注意,在赋值运算符重载中,需要先判断两个对象是否相同,如果相同,则不需要进行赋值操作。