c++ - 在 C++ 的析构函数中调用 delete[]

标签 c++ memory-management memory-leaks destructor assignment-operator

我对下面的代码有疑问,析构函数中有一个析构函数delete line[],我只是想知道这个删除是否有任何堆栈溢出,这可能是一个结果递归调用析构函数。

class Line {
public:
    char *line;
    Line(const char *s = 0) {
        if (s) {
            line = new char[strlen(s)+1];
            strcpy(line, s);
        } else {
            line = 0;
        }
    }

    ~Line() {
        delete[] line; //----------> how this delete will work?
        line = 0;
    }

    Line &operator=(const Line &other) {
        std::cout <<"go"<< endl;
        delete[] line; //----------> purpose of using this delete??
        line = new char[other.len()+1];
        strcpy(line, other.line);
        return *this;
    }

    int operator<=(const Line &other) {
        int cmp = strcmp(line, other.line);
        return cmp <= 0;
    }

    int len() const {
        return strlen(line);
    }
};





int main() {
Line array[] = {Line("abc"), Line("def"),
                Line("xyz")};
   Line tmp;
  }

重载赋值运算符中的delete是在分配新内存之前清理内存(我在某处读到过,如果我错了请指正),但是这个delete会调用析构函数吗?

请解释一下

最佳答案

不,不会。

此删除语句将删除 char 数组。 Line的析构函数仅在销毁Line对象时被调用。但这里的情况并非如此。

变量 line 和对象/类 Line 是不同的东西。

line 变量是 Line 类中的成员变量。所以这两个名字看似相同,实则完全不同。

关于c++ - 在 C++ 的析构函数中调用 delete[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47904269/

相关文章:

c++ - 调用构造函数而不创建对象

c++ - 对 'Inventory::insertEnd(Node*, int)' 的 undefined reference

C++ -- 智能指针和自定义内存分配困境

ios - methodSignatureForSelector 内存泄漏

android - 使用 Android NDK 构建 VPNC

c++ - 我可以为 C++ 类提供不完整的 header 以隐藏实现细节吗?

c++ - 尽管有 pop(),如何避免删除 priority_queue::top()?

opencv - cv::Ptr<CvHaarClassifierCascade> 是如何被释放的?

C++ 从原始数组构造 vector 而不进行复制

javascript - Node.js 进程中运行的 setInterval 导致内存泄漏