C++ 如何编写析构函数来删除一棵树,其中每个节点都是一个动态分配的结构,包含多个数组?

C++ 如何编写析构函数来删除一棵树,其中每个节点都是一个动态分配的结构,包含多个数组?,c++,oop,C++,Oop,我有一个类,它包含一个名为Node的结构,内存是动态分配的。使用add函数,我创建了更多的节点,并通过下一个数组指针将它们连接起来。我只保存指向第一个节点的头指针。我正试图写一个如下所示的析构函数。可以吗 struct Node{ bool arr[30]; bool end[30]; Node* next[30]; }; class ClassName{ Node *head; Node* newNode(){ Node * cur

我有一个类,它包含一个名为Node的结构,内存是动态分配的。使用add函数,我创建了更多的节点,并通过下一个数组指针将它们连接起来。我只保存指向第一个节点的头指针。我正试图写一个如下所示的析构函数。可以吗

struct Node{
    bool arr[30];
    bool end[30];
    Node* next[30];
};

class ClassName{
    Node  *head;
    Node* newNode(){
        Node * cur = (Node*)malloc(sizeof(Node));
        return cur;
    }
public:
    ClassName(){
        head = newNode();
    }
    ~ClassName(){
        free(head);
    }
    void add(string s,int pos,Node *cur){// 1 base index
        // adding new node and next array pointers will connect them
        // So after adding some nodes it will form like a tree
    }
};
这将释放头部节点。它也不会释放head->next[0..29]引用的任何节点。所以不,如果你真的分配了那些节点,那就不好了——你会有内存泄漏

下一个问题是,您的下一个数组未初始化,因此除非它总是全部填充(这显然是不可能的,因为您的树没有叶子),否则无法确定哪些条目是真正的指针,哪些是垃圾值。因此,用如图所示的代码修复此漏洞是不可能的

我们可以修复现有的Maloc代码来正确初始化对象,但是它会把我们带到下一个怪异的地方,即使用MALOC和免费的C++对象。 使用new和delete将是一个适度的改进,至少Node可以有一个构造函数和析构函数来正确初始化和销毁自己,但切换到拥有智能指针而不是原始指针将是最好的:它们自动初始化和销毁自己,而无需您额外的工作

struct Node{
    // value-initialize all those bools to false
    bool arr[30] {};
    bool end[30] {};
    // this will initialize all entries to nullptr, and
    // also takes care of deleting them on destruction
    std::array<std::unique_ptr<Node>, 30> next;
};

    std::unique_ptr<Node> ClassName::newNode() {
        return std::make_unique<Node>();
    }

为什么使用malloc和free而不是new和delete?使用add函数,我创建了更多节点,并通过下一个数组指针将它们连接起来。-您的节点无法直观地显示您实际想要实现的目标—描述add应该做什么并不是足够的信息。我们需要看看add是做什么的。如果你想使用new和delete,我会问你为什么不使用a来代替呢?使用智能指针进行递归的析构函数已经在大型图中咬了我好几次了。确保图形的大小足够小,以至于您不能或不太可能溢出堆栈。
struct Node{
    // value-initialize all those bools to false
    bool arr[30] {};
    bool end[30] {};
    // this will initialize all entries to nullptr, and
    // also takes care of deleting them on destruction
    std::array<std::unique_ptr<Node>, 30> next;
};

    std::unique_ptr<Node> ClassName::newNode() {
        return std::make_unique<Node>();
    }