【发布时间】:2023-03-15 16:12:02
【问题描述】:
我有这个树结构:
public:
node(string& const n);
virtual ~node();
string get_name() const;
void set_name(string& new_name);
int get_nr_children() const;
node get_child(int i) const;
void add_child(node child);
private:
string& name;
vector<node> children;
};
我的 main.cpp 看起来像这样:
int main() {
string s = "root";
node r(s);
string s2 = "left child";
node ls(s2);
string s3 = "right child";
node rs(s3);
r.add_child(ls);
r.add_child(rs);
r.~node();
}
(我知道~node() 在main 函数的末尾无论如何都会在所有对象上运行,但我想确保它首先在根r 上执行)
到目前为止,所有方法都运行良好,除了析构函数。这是我的第一个析构函数,我想出了下面的递归尝试,但不知道为什么它不起作用。
node::~node() {
cout << "Enter ~node of " << this->get_name() << endl;
while (this->get_nr_children() != 0) {
this->get_child(0).~node();
this->children.pop_back();
}
delete this;
cout << "Leave ~node of " << this->get_name() << endl;
}
结果是“Enter ~node of left child”的无穷输出
【问题讨论】:
-
不要不直接调用析构函数。而是使用
delete(更好的是:使用容器或智能指针)。 -
但仅在指向您使用
new分配的对象的指针上调用delete。 -
delete this来自析构函数?真的吗? -
void main在 C 或 C++ 中从未有效。带有void main的代码会教给初学者一个坏习惯,这意味着大多数读者不能只是复制和粘贴代码来尝试一下。请不要使用void main发布代码。谢谢你。 FTFY。 -
@PattuX 让智能指针甚至是相关的,你需要有指针......你似乎根本没有。您的孩子是
node中的vector,因此与delete无关。
标签: c++ tree destructor