使用前释放列表的节点

Nodes of a list being freed before usage

我有一个包含节点的一维模板列表,每个节点都有一个 link 到下一个节点。 它本身运行良好,但当它包含另一个 linked 列表时就不行了。

LinkedList 和 Node 看起来像这样:

template <class T> 
class LinkedList 
{ 
    private:
        Node<T>* pPreHead; 
    public:
        LinkedList(void);
        ~LinkedList(void);
        Node<T>* getHead(void);
        int size();
        void addElementToEnd(T& value);
        void deleteNextNode(Node<T>* pNodeBefore);
}

template <class T>
class Node 
{
    private:
        T value;
        Node* next;
    public:
        Node();
        Node* getNext();
        Node* getValue();
        void setNext(Node* nextElem);
        void setValue(T elem);
};

现在,对于我需要使用 LinkedList> 的任务,它是通过循环填充的。 它看起来像这样:

ifstream fl;
fl.open("test1.in", std::ifstream::in);
while (fl.good())
{
    string currentLine;
    getline(fl, currentLine);

    LinkedList<string> newDNA;

    //newDNA being filled here so I skipped code

    DNAStorage.addElementToEnd(newDNA);

    //Place 1
}

//Place 2

现在,如果我在 "Place 1" 中插入一些测试输出代码,一切都很好,但是当循环进入新的迭代时 newDNA 变量被释放,DNAStorage 中的指针也被释放(这是 LinkedList<LinkedList<string>> 的问题),当我尝试在 "Place 2" 中打印任何内容时,出现分段错误。

不幸的是,我不能使用任何其他数据结构,因为这是我需要完成的任务。 我的问题是 - 如何解决这个问题,使其实际上不会过早释放?

编辑: 这是我的 AddElementToEnd(T& value):

代码
template <class T>
void LinkedList<T>::addElementToEnd(T &value)
{
    Node<T> *newtail = new Node<T>;
    newtail.setNext(NULL);
    newtail.setValue(value);

    if(pPreHead == NULL)
    {
        pPreHead = newtail;
        return;
    }

    Node<T> *tail = pPreHead;
    while(tail.getNext() != NULL)
    {
        tail = tail.getNext();
    }

    tail.setNext(newtail);
}

问题是您正在存储对超出范围的对象的引用,从而在您尝试访问它们时导致未定义的行为。您的 LinkedList<string> newDNA 会随着 while 循环的每次迭代而创建和销毁,但您传递了一个要存储在 DNAStorage 列表中的引用。

一个解决方案是在调用 addElementToEnd() 时在列表中存储每个对象(不是引用)的副本。