代码之家  ›  专栏  ›  技术社区  ›  Guy_Hanan

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

  •  0
  • Guy_Hanan  · 技术社区  · 1 年前

    我收到这段代码作为一项任务,其中一个问题是:程序中是否会因为MyList的析构函数释放节点而不释放数据而出现内存泄漏。 当执行删除节点时,字符串类是否会自行释放内存?如果模板变量不是字符串或其他什么。。。简而言之,我不明白这里是否有问题。释放节点内存时会发生什么?

    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;
            });
        });     
    }
    

    我不知道当Node发布时,它内部的功能是否也发布了。我希望得到有关这方面的答复。

    1 回复  |  直到 1 年前
        1
  •  1
  •   Chris    1 年前

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

    考虑这样的案例 MyList<int *> 其中列表中的每个元素都是指向 int 。我们不希望破坏列表就破坏原始列表 int 值节点的 数据 成员指向,特别是因为它们可能一开始就没有被动态分配。