Shared_ptr双重链表内存泄漏

时间:2020-01-25 02:00:36

标签: c++ memory-leaks shared-ptr doubly-linked-list

尽管使用smart_ptr,但我遇到了一些内存泄漏。

wdio

2 个答案:

答案 0 :(得分:3)

这是因为这形成了一个循环,共享的ptr无法处理该循环。

例如,列表中有两个节点ab

{
    linkedlist l;
    {
        std::shared_ptr<node> a{new node};
        std::shared_ptr<node> b{new node};
        // a count: 1, b count: 1
        a.next = b;
        b.prev = a;
        // a count: 2, b count: 2
        l.head = a;
        l.tail = b;
        // a count: 3, b count: 3
    }
    // a count: 2, b count: 2  (local variables destructed)
}
// a count: 1, b count: 1 (l, l.head and l.tail destructed)
// count != 0, so not deleted and memleak

要解决此问题,请将node.prevlinkedlist.tail设为std::weak_ptr,以防止节点通过node.prev.nextnode.next.prev间接持有对自己的强引用 >

答案 1 :(得分:0)

这是工作代码

#include <iostream>
#include <memory>
using namespace std;
class linkedlist{
public:
    linkedlist(){}
    void inserthead(int value){
        shared_ptr<node> temp=make_shared<node>(value);
        if(head==nullptr){
            head=temp;
            tail=head;
        }else{
            head->prev=temp;
            temp->next=head;
            head=temp;
        }
    }
    void inserttail(int value){
        shared_ptr<node> temp=make_shared<node>(value);
        if(head==nullptr){
            head=temp;
            tail=head;
        }else{
            temp->prev=tail;
            auto ptr=tail.lock();
            ptr->next=temp;
            tail=temp;
        }

    }
    void print(){
        shared_ptr<node> temp=head;
        while (temp!=nullptr)
        {
            cout<<temp->data<<endl;
            temp=temp->next;
        }
    }
private:
    struct node{
        node(int value):data(value){
        }
        weak_ptr<node> prev;
        shared_ptr<node> next{nullptr};
        int data;
    };
    shared_ptr<node> head{nullptr};
    weak_ptr<node> tail;
};