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

时间:2016-04-12 01:31:37

标签: c++ templates pointers unique operator-keyword

我试图在双向链表中系统地实例化持有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; 9&#39;的同一学生对象的实例。作为参数。

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

没有可行的转换来自&#39; Node *&#39;至       &#39;节点&#39;

我非常感谢对问题的任何洞察或推动正确的方向。

1 个答案:

答案 0 :(得分:1)

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>