簡體   English   中英

如何釋放由鏈表實現的隊列 class 的成員函數動態分配的 memory?

[英]How to free the memory that is dynamically allocated by member functions of a Queue class which is implemented by Linked List?

我用鏈表實現了一個隊列 class,它具有pushpop功能。 push function 每次調用都會用new操作符動態分配一些memory。 我的問題是:

  1. 如何釋放這些由push function 分配的 memory(假設沒有調用 pop)? 我寫的析構函數有用嗎?
  2. 如果我要通過Queue* queue2 = new Queue(); ,調用delete queue2 queue2 是否會釋放由push function 分配的 memory (假設沒有調用 pop)?

下面是我寫的代碼:

struct ListNode { 
    ListNode* next;
    int val;
    ListNode(int x) {
        val = x;
        this->next = nullptr;
    }
};

class Queue {
public:
    Queue() {
        head = nullptr;
        tail = nullptr;
    }
    
    // Destructor for freeing all dynamically allocated memory
    ~Queue(){
        if (head){
            ListNode* cur = head;
            ListNode* next;
            // iterate through the list and free all memory
            while (cur){
                next = cur->next;
                delete cur;
                cur = next;
            }
            head = nullptr;
        }
    }

    void push_front(int x) { // add node at then end of linked list
        // Need to dynamically allocate front bc want it to persist after leaving this block
        ListNode* front = new ListNode(x);
        if (!head) {
            head = front;
            tail = head;
        }
        else {
            tail->next = front;
            tail = tail->next;
        }
    }

    void pop_back() { // remove the first node of the linked list
        if (!head) {
            return;
        }
        ListNode* newHead = head->next;
        delete head; // free memory
        head = newHead;
    }

private:
    ListNode* head;
    ListNode* tail;
};


int main() {
    Queue queue = Queue();
    queue.push_front(1);
    queue.push_front(2);
}

是的,通常在 object 的生命周期內分配的東西在 object 被銷毀時在析構函數中被取消分配。

所以回答你的第一個問題。 是的,析構函數看起來像是在做正確的事情。


未提出的問題是您的代碼做得足夠好。
答案是否定的。 問題是編譯器會自動生成一些不適用於動態分配的方法,並且您必須提供手動實現。

因此,您的 class 缺少復制構造函數和復制賦值運算符。 這被稱為三法則(復制構造函數/復制分配/析構函數)。

{
    Queue   a;
    a.push_front(1);

    Queue   b(a);   // Problem is here.
                    // The default generated copy constructor
                    // creates a shallow copy of the object.
}
// the destruction of the objects b and a interact resulting in
// a double de-allocation of your ListNode.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM