自定义字符串类和析构函数

Custom string class and destructors?

本文关键字:析构函数 字符串 自定义      更新时间:2023-10-16

我今天很无聊,我想创建自己的小字符串类。我真的很喜欢 .Net 中的"System.String"类,因为它是拆分/替换/删除等函数,我想尝试实现它们。

然而,我的问题是析构函数。如果我的字符串类有多个实例保存相同的字符串,那么在调用析构函数时,所有这些实例都会尝试删除相同的内存吗?

例如:

void DoSomething() {
    MyStringClass text = "Hello!";
    {
        MyStringClass text2 = text;
        // Do something with text2
    } // text2 is destroyed, but so is the char* string in memory
    // text now points to useless memory??
}

我理解对吗?哈哈。

谢谢

亚历克斯

编辑:

哎呀,我忘了包含代码:

class string {
    unsigned int length;
    char* text;
public:
    string() : length(0), text(NULL) { }
    string(const char* str) {
        if (!str) throw;
        length = strlen(str);
        text = new char[length];
        memcpy(text, str, length);
    }
    ~string() {
        delete[] text;
    }
};

你是对的 - 两者都会尝试delete []相同的内存块。

您没有为类定义复制构造函数,因此您将获得默认构造函数,该构造函数执行指针的浅表副本。

text2超出范围时,指针将delete [] d。 当text1超出范围时,同一指针将再次delete [] d,从而导致未定义的行为。

有许多方法可以解决这个问题,最简单的方法是定义复制构造函数和赋值运算符。