首页 > 解决方案 > 如何在 C++ 类中删除它(使其不进入无限循环)

问题描述

class double_node{
public:
    // Data members
    ll data;
    double_node * next;
    double_node * prev;

    // Functions
    double_node(){
        this->next = nullptr;
        this->prev = nullptr;
        this->data = LLONG_MIN;
    }

    double_node(ll data, double_node * next, double_node * prev){
        this->data = data;
        this->next = next;
        this->prev = prev;
    }

    // WARNING : Memory Leak
    // I don't know why defining a destructor gives an error
     ~double_node(){
         cerr << "~double_node() is called\n";
          if(this != nullptr){
              delete this;
          }
     }
};

class double_linked_list{
public:
    double_node * head = new double_node;
    double_node * tail = new double_node;

    double_linked_list(){
        // Head part
        head->data = LLONG_MIN;
        head->next = tail;
        head->prev = nullptr;
        // Tail part
        tail->data = LLONG_MIN;
        tail->next = nullptr;
        tail->prev = head;
        
    }
    void append(ll data){
        if(head->data == LLONG_MIN){
            head->data = data;
        }
        else if(tail->data == LLONG_MIN){
            tail->data = data;
        }
        else{
            double_node * temp = tail;
            double_node * last = new double_node;
            
            // Setting up last
            last->data = data;

            temp->next = last;
            last->prev = temp;
            last->next = nullptr;

            tail = last;
        }
        
    }

    void remove(ll data){
        double_node * temp = head;
        while(temp != nullptr and temp->data != data){
            temp = temp->next;
        }
        if(temp->data == data){
            double_node * y = temp->prev;
            double_node * x = temp;
            double_node * z = temp->next;
            if (z != nullptr){
                z->prev = y;
            }
            if(y != nullptr){
                y->next = z;
            }
            if(x == head){
                head = z;
            }
            if(temp != nullptr){
                x->next = nullptr;
                x->prev = nullptr;
                delete x;
            }

        }
    }
};

标签: c++linked-listc++17doubly-linked-list

解决方案


如何在 C++ 类中删除它(使其不进入无限循环)

通过不删除this. 永远不要在析构函数中这样做。而且几乎没有理由在任何功能中这样做。

只需~double_node完全删除。该节点不拥有任何资源,因此不需要用户定义的析构函数。

我遇到了内存泄漏的问题。

您需要~double_linked_list在节点上定义循环并删除它们。您还需要遵循5 的规则


推荐阅读