一个关于C++程序内存泄漏的问题

问题描述 投票:0回答:1

我收到了这段代码作为作业,其中一个问题是:程序中是否会出现内存泄漏,因为MyList的析构函数释放了节点但没有释放数据。 删除节点时string类会自行释放内存吗?而且如果模板变量不是字符串或者其他东西...总之,我无法理解这里是否有问题,我也在Visual Studio中运行了程序,但找不到答案。当节点内存被释放时会发生什么?谢谢 !!! 代码:

template<class E> class MyList 
{
    class Node 
    {
        friend class MyList<E>;
        E data;
        Node* next = nullptr;
        ~Node() {  }
    };

    Node* head = new Node;
    Node* tail = head;
    Node* createNode(const E& data, Node* prev)
    {
        Node* node = new Node;
        node->data = data;
        node->next = prev->next;
        prev->next = node;
        return node;
    }
    public:
    MyList() = default;
    MyList(const MyList&) = delete;
    MyList& operator =(const MyList&) = delete;

    void push_front(const E& data) 
    {
        Node* node = createNode(data, head);
        if (tail == head) tail = head;
    }
    void push_back(const E& data)
    {
        tail = createNode(data, tail);
    }

    ~MyList() 
    {
        Node* node = head, * next;
        while (node != nullptr)
        {
            next = node->next;
            delete node;
            node = next;
        }
    }

    template<class Function>
    void apply(Function f)const 
    {
        Node* node = head->next;
        while (node != nullptr)
        {
            f(node->data);
            node = node->next;
        }
    }
};

int main()
{
    MyList<std::string>m3;
    m3.push_back("Hello");
    m3.push_back("World");
    MyList<MyList<std::string>*> m4;
    m4.push_front(&m3);
    m4.push_back(&m3);
    m4.apply([](auto plist)
    {
        plist->apply([](const auto& val) 
        {
            std::cout << val << std::endl;
        });
    });     
}

我尝试在 Visual Studio 中运行该程序并得到答案,但我仍然不明白。 我不知道当 Node 发布时,它内部的功能是否也发布了。我希望得到有关此问题的答案。

c++ memory memory-leaks
1个回答
0
投票

MyList
类的析构函数不会泄漏内存,除非
Node
对象有责任拥有它们可能包含的任何指针所指向的数据。当节点被销毁时,节点的
data
成员也会被销毁。

考虑像

MyList<int *>
这样的情况,其中列表中的每个元素都是指向
int
的指针。我们不希望销毁列表会销毁节点的
int
成员指向的原始
data
值,特别是因为它们可能一开始就没有被动态分配。

© www.soinside.com 2019 - 2024. All rights reserved.