如何删除单链表节点内的指针?删除节点时内部对象指针会被释放吗?
单链表节点删除时内部指针内存释放问题
不会自动释放。
当你执行delete node;时,只会释放Node对象本身占用的内存——也就是Node类里的c指针和next指针这两个变量的内存,但它们指向的堆内存(这里是customer对象)不会被自动回收,这会导致内存泄漏:new customer(5)分配的内存永远无法被释放,直到程序结束。
解决方法
方法1:给Node添加析构函数手动释放
在Node类中添加析构函数,在析构时主动删除c指向的customer对象,这样delete node时会自动调用析构函数,连带释放customer的内存:
struct customer{ int data; customer(int data){ this->data= data; } }; class Node{ public: customer * c; Node * next; Node(customer *&x){ this->c = x; this->next = nullptr; } // 新增析构函数 ~Node(){ delete c; // 释放customer对象的内存 } }; int main() { customer * khach = new customer(5); Node * node = new Node(khach); delete node; // 此时会先调用Node的析构函数释放c指向的内存,再释放node自身 }
方法2:使用智能指针自动管理内存
C++11及以上推荐使用智能指针(比如std::unique_ptr)来替代裸指针,它会在对象生命周期结束时自动释放内存,无需手动调用delete:
#include <memory> struct customer{ int data; customer(int data){ this->data= data; } }; class Node{ public: std::unique_ptr<customer> c; std::unique_ptr<Node> next; Node(std::unique_ptr<customer> x){ this->c = std::move(x); this->next = nullptr; } }; int main() { auto khach = std::make_unique<customer>(5); auto node = std::make_unique<Node>(std::move(khach)); // 无需手动delete,智能指针会在main函数结束时自动释放所有内存 }
内容的提问来源于stack exchange,提问作者Trung Pham
相关产品推荐
相关产品推荐

