MST

星途 面试题库

面试题:C++类拷贝构造函数中深拷贝的实现及注意事项

假设你有一个包含动态分配内存成员的C++类,如一个字符串指针成员。请实现该类的深拷贝构造函数,并说明在实现过程中需要注意哪些内存管理问题,以避免内存泄漏和悬空指针等情况。
14.6万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试

代码实现

#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;
    }
};

内存管理注意事项

  1. 分配足够内存:在深拷贝构造函数中,为新对象的字符串指针分配与原对象相同大小的内存,包括字符串结束符'\0'的空间。如str = new char[strlen(other.str) + 1];
  2. 复制内容:使用strcpy等函数将原对象字符串内容复制到新分配的内存中,确保内容一致。strcpy(str, other.str);
  3. 释放旧内存:在赋值运算符重载函数中,先释放当前对象已有的内存,避免内存泄漏。delete[] str;
  4. 避免自赋值:在赋值运算符重载中,通过if (this != &other)判断,防止对象自我赋值,避免悬空指针和重复释放内存的问题。
  5. 正确析构:确保在析构函数中正确释放动态分配的内存,如delete[] str;,防止内存泄漏。