C++使用new在循环中创建唯一的对象指针

C++ using new to create unique object pointers within a loop

本文关键字:唯一 对象 指针 创建 使用 new 循环 C++      更新时间:2023-10-16

我正试图系统地实例化在双链表中持有Student类型对象的节点。当我手动创建节点并将它们添加到列表中时,我的双链接列表运行良好,但当我在循环中实例化节点时,指针会被覆盖。

为了编写这段代码,我需要根据文本文件的输入实例化一定数量的节点,所以我必须使用循环。

DoublyLinkedList<Student> dlist;
for(int j = 0; j<numOfStudents;j++)
{
    getline(myfile,line);
    Student student1 =  Student(toInt(line));     //toInt() converts string to Int
    Node<Student> node1 = Node<Student> (student1);
    dlist.add(&node1);
}   

不过,我遇到的问题是,如果一个文本文件对学生有以下参数。

6

11

9

然后,双链接列表将简单地填充3个具有"9"作为参数的同一学生对象实例。

在研究这个问题时,我发现使用新的运算符会为每个对象提供一个唯一的指针,只要我稍后删除它以防止内存泄漏。但是,在尝试通过在Node前面添加新的来实现它时,我收到了一个错误,即存在

没有从"节点*"到的可行转换"节点"

我非常感谢对这个问题的任何见解或朝着正确的方向努力。

for(int j = 0; j<numOfStudents;j++)
{
    getline(myfile,line);
    Student student1 =  Student(toInt(line));     //toInt() converts string to Int
    Node<Student> node1 = Node<Student> (student1);
   dlist.add(&node1);

}

我们有两个问题。

首先,student1和node1在循环中只有作用域。这意味着当循环退出时,列表中的数据将不再有效。student1中的数据可能在node1的构建中被复制,这使得student1只在循环中起作用的事实是不可否认的,但node1肯定是一个问题。

其次,将指向node1的指针添加到numOfStudents次数列表中。

一种解决方案涉及为"节点"分配内存

for(int j = 0; j<numOfStudents;j++)
{
    getline(myfile,line);
    Student student1 =  Student(toInt(line));     //toInt() converts string to Int
   // Create a new node to add to the list 
   Node<Student> *node1 = new Node<Student> (student1);
   // Add the node to the list
   dlist.add(node1);
}

这里需要记住的重要一点是,当您从列表中删除元素时,它们必须在处理完后释放。

delete <pointer to allocated node>