【发布时间】:2026-01-09 18:00:02
【问题描述】:
我对下面的代码有疑问,析构函数内部有一个析构函数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会调用析构函数吗?
请解释
【问题讨论】:
-
line是一个指向char的指针,它没有析构函数。在它上面调用delete将释放你分配的内存,仅此而已。 -
正如答案所说,没有递归。但是,如果有人这样做
Line l("Hello World); Line *p = &l; l = *p;,您的复制分配代码就会出现问题。这是自我分配,而且非常错误。最好的解决方案是 1. 编写一个合适的拷贝构造函数。 2. 为 Line 编写 std::swap 的特化。 3. 复制赋值采用other按值,而只采用std::swap(*this, other); return *this;。如果您的交换是不抛出(应该是),那么这提供了强大的异常保证。
标签: c++ memory-management memory-leaks destructor assignment-operator