我对下面的代码有疑问,析构函数中有一个析构函数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/