You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++双向链表:如何验证析构函数实现的正确性

搞定双向链表析构函数的测试:节点删除前打印地址

嘿,我来帮你解决这个问题!要实现「每个节点被删除前输出地址」的需求,核心是在双向链表的析构函数里加打印逻辑——毕竟析构函数就是负责销毁链表所有节点的地方,这正是我们要拦截节点删除的最佳时机。下面是具体的实现步骤和代码:

1. 给你的双向链表类补全析构逻辑

假设你的DoublyLinkedList已经有了基本的节点结构和链表操作,你只需要修改析构函数,遍历每个节点,在delete前打印它的地址就行:

#include <iostream>
using namespace std;

class DoublyLinkedList {
private:
    // 假设你的节点结构是这样的(如果不一样可以调整)
    struct Node {
        int data;
        Node* prev;
        Node* next;
        Node(int val) : data(val), prev(nullptr), next(nullptr) {}
    };
    Node* head;
    Node* tail;

public:
    // 构造函数初始化头尾指针
    DoublyLinkedList() : head(nullptr), tail(nullptr) {}

    // 给个插入节点的方法,方便后续测试
    void push_back(int val) {
        Node* newNode = new Node(val);
        if (!head) {
            head = tail = newNode;
        } else {
            tail->next = newNode;
            newNode->prev = tail;
            tail = newNode;
        }
    }

    // 重点!修改析构函数,添加打印逻辑
    ~DoublyLinkedList() {
        Node* current = head;
        while (current != nullptr) {
            // 删除前先打印当前节点的内存地址
            cout << "Deleting node at address: " << current << endl;
            // 先存下下一个节点的指针,避免delete后找不到
            Node* temp = current;
            current = current->next;
            delete temp;
        }
        // 可选:清空头尾指针,防止野指针
        head = tail = nullptr;
    }
};

2. 在main里写测试函数验证

你之前写的void cList()可以改成一个测试函数,在里面创建链表、插入节点,然后让链表对象自动销毁(比如函数结束时离开作用域),这样就会触发析构函数:

// 你的测试函数可以写成这样
void testDestructor() {
    DoublyLinkedList a;
    cout << "Inserting nodes: 0, 1, 2, 3" << endl;
    // 循环插入测试节点
    for (unsigned i = 0; i < 4; ++i) {
        a.push_back(i);
    }
    // 当函数执行到这里结束时,a会自动销毁,调用析构函数
}

int main() {
    testDestructor();
    cout << "Destructor test finished!" << endl;
    return 0;
}

3. 运行效果参考

运行程序后,你会看到类似这样的输出(地址是实际内存地址,每次运行可能不一样):

Inserting nodes: 0, 1, 2, 3
Deleting node at address: 0x55a8d7c22eb0
Deleting node at address: 0x55a8d7c22ed0
Deleting node at address: 0x55a8d7c22ef0
Deleting node at address: 0x55a8d7c22f10
Destructor test finished!

额外提示

如果你的链表还有其他删除节点的方法(比如pop_front、erase指定节点),也可以在这些方法里加同样的打印逻辑,这样不管是析构时批量删除,还是手动删除单个节点,都能输出地址啦!

内容的提问来源于stack exchange,提问作者nc052

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:34:09