C ++析构函数被意外地称为双链表

问题描述 投票:0回答:1
    doubly_linked_list::~doubly_linked_list()
{
    list_item* current = head;
    while (current)
    {
        list_item* next = current->Get_Next();
        delete current;
        current = next;
    }
}

我正在用C ++编写一个动态图,并使用一个双向链接列表来保存Graph节点,但是我的代码不断失败,因为它调用析构函数的次数比应调用的次数多,例如在析构函数期间对于图表

    Dynamic_Graph::~Dynamic_Graph()
{
    edges.~doubly_linked_list();
    nodes.~doubly_linked_list();
}

双向链表的析构函数被调用了两次以上,尽管它被显式调用了两次。

然后我具有插入边缘的功能:

Graph_Edge* Dynamic_Graph::Insert_Edge(Graph_Node* from, Graph_Node* to)
{
    Graph_Edge* new_edge = new Graph_Edge(from, to);
    from->Get_out_Nodes().List_Insert_After(to, from->Get_out_Nodes().Get_Tail());
    to->Get_in_Nodes().List_Insert_After(from, to->Get_in_Nodes().Get_Tail());
    edges.List_Insert(new_edge);
    return new_edge;
}

在将to节点添加到from节点的邻接列表之后,代码无法解释地调用了双向链接列表的析构函数,并删除了此插入,但是我不确定为什么。

这里是图形和链接列表的标题:

class doubly_linked_list
{
private:
    list_item* head;
    list_item* tail;
public:
    doubly_linked_list() { this->head = NULL; this->tail = NULL; }
    doubly_linked_list(list_item* head){ this->head = head; this->tail = NULL; }
    ~doubly_linked_list();
    list_item* Get_Head() { return head; }
    list_item* Get_Tail() { return tail; }
    void Set_Head(list_item* h) { head = h; }
    void List_Insert(list_item* x);
    void List_Insert_After(list_item* x, list_item* y);
    void List_Delete(list_item* x);
};


class Dynamic_Graph
{
protected:
    doubly_linked_list edges;
    doubly_linked_list nodes;
public:
    Dynamic_Graph() { edges = doubly_linked_list(); nodes = doubly_linked_list(); }
    ~Dynamic_Graph();
    Graph_Node* Insert_Node(unsigned node_key);
    void Delete_Node(Graph_Node* node);
    Graph_Edge* Insert_Edge(Graph_Node* from, Graph_Node* to);
    void Delete_Edge(Graph_Edge* edge);
    Rooted_Tree* SCC() const;
    Rooted_Tree* BFS(Graph_Node* source) const;
};

欢迎任何帮助

c++ graph doubly-linked-list
1个回答
0
投票

您不应该手动调用析构函数。它们会自动为您调用。

您只需要在通过调用delete实际创建的对象上使用new(也称为析构函数)。达到其范围的末尾时,将自动销毁所有其他对象,然后将自动调用其析构函数。对于班级成员也是如此。

这里唯一的例外是,如果您使用placement-new创建对象,或者打算重新使用其存储。但是您可能不打算这样做。

完全删除Dynamic_Graph的析构函数。不需要。

© www.soinside.com 2019 - 2024. All rights reserved.