C ++为什么会导致内存泄漏?

时间:2015-11-19 21:23:29

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

如果我们有以下简单的双链表:

class Node{
    //...

    Node* next;
    Node* previous;
    int data;
};

class A{
    //...
    A(const A&);
    ~A(); //goes through list and deletes each node
    A& operator=(const A&);

    Node* begin;
    Node* end;
    int id;
};

A::A(const A& copyThis)
{
    //creates a new list that represnets the same data as copyThis's list
    //but is not the same list
    //Example for clarification:
    //if copyThis represented a list of nodes each containing the values 1-10 respectively
    //this constructor would make a new list of nodes each containing the values 1-10
    //and make the invoking object's members point to the beginning and end of it
    //assume this does not create any memory leaks
}

A& A::operator=(const A& a) //this causes a memory leak
{
    A* aCopy = new A(a); //now 'a' and 'this' should represent the same
    //values but point to different lists
    this->begin = aCopy->begin;
    this->end = aCopy->end;
    this->id = aCopy->id;

    //code here that deletes list that invoking object used to point to
    //assume it does correctly and without memory leak

    return *this;
}

让我们说我们有这个功能:

void foo()
{
    A a1(); 
    //put some data into a1
    A a2();
    {a2=a1;}
}

我的问题是为什么这会导致内存泄漏,因为a2应该代表Node aCopyoperator=内部和a2内所做的同一个aCopy列表超出范围,它可以正确释放为每个节点分配的内存。

修改: 好吧所以我在发布这个问题之后才意识到可能会创建newNodedrop=分配内存而不仅仅是它所代表的keep=,并且永远不会释放内存。这是对的吗?

修改: 我不是要求更好或更正确的方法来编写此代码,我只是要求解释为什么这会导致内存泄漏。

1 个答案:

答案 0 :(得分:0)

一方面,operator =需要返回T&。您正在泄漏aCopy指向的内存。你完全不需要它。你应该做这样的事情:

A& A::operator=(const A& a)
{
    this->begin = a.begin;
    //etc.
    return *this;
}