C++使用new在循环中创建唯一的对象指针
C++ using new to create unique object pointers within a loop
我正试图系统地实例化在双链表中持有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>
相关文章:
- C++优先级队列,按对象的唯一指针的特定方法升序排列
- 如何使用Visual Studio 2017在C++中为参数化对象数组使用唯一指针
- 使用Unique_ptr确保工厂中的对象唯一
- 具有引用成员的结构是否具有唯一的对象表示形式
- 堆分配的对象是否存在永不为空的唯一所有者?
- 如何在C++中为增加但记住删除先前对象的对象分配唯一标识符
- 添加要映射的对象的唯一指针
- 唯一命名对象的表
- 在创建对象向量时,不为每个对象唯一调用默认对象构造函数
- 唯一 ptr 将所有权移动到包含对象的方法
- 如何打印出唯一指针对象向量中的值(基于范围的循环)?C++
- 当原始指针和唯一指针都引用同一对象时,如何避免双重释放
- 将对象数组转换为指向唯一对象的指针数组
- 我如何模拟将作为唯一_ptr存储在gmock中的对象
- 使用具有唯一随机数的结构数组创建多个对象
- 确定 std::shared_ptr 是否是对对象的唯一引用
- 如何在 C++ 中插入和排序具有唯一条目的对象向量
- 唯一的指针在移动后仍然容纳对象
- 敌人幽灵实例/非唯一对象
- 无法成功创建唯一对象的std::列表