代码实现
#include <iostream>
#include <cstring>
class MyClass {
private:
char* str;
public:
// 构造函数
MyClass(const char* s = nullptr) {
if (s) {
str = new char[strlen(s) + 1];
strcpy(str, s);
} else {
str = new char[1];
*str = '\0';
}
}
// 深拷贝构造函数
MyClass(const MyClass& other) {
if (other.str) {
str = new char[strlen(other.str) + 1];
strcpy(str, other.str);
} else {
str = new char[1];
*str = '\0';
}
}
// 析构函数
~MyClass() {
delete[] str;
}
// 赋值运算符重载
MyClass& operator=(const MyClass& other) {
if (this != &other) {
delete[] str;
if (other.str) {
str = new char[strlen(other.str) + 1];
strcpy(str, other.str);
} else {
str = new char[1];
*str = '\0';
}
}
return *this;
}
};
内存管理注意事项
- 分配足够内存:在深拷贝构造函数中,为新对象的字符串指针分配与原对象相同大小的内存,包括字符串结束符
'\0'
的空间。如str = new char[strlen(other.str) + 1];
- 复制内容:使用
strcpy
等函数将原对象字符串内容复制到新分配的内存中,确保内容一致。strcpy(str, other.str);
- 释放旧内存:在赋值运算符重载函数中,先释放当前对象已有的内存,避免内存泄漏。
delete[] str;
- 避免自赋值:在赋值运算符重载中,通过
if (this != &other)
判断,防止对象自我赋值,避免悬空指针和重复释放内存的问题。
- 正确析构:确保在析构函数中正确释放动态分配的内存,如
delete[] str;
,防止内存泄漏。