C++自定义队列入队成功但print打印无内容问题排查
问题描述
我正在尝试向队列中入队数据。
入队操作看似执行成功:当前Node节点的Thing指针不为空,其存储的Thing对象id为预期值7。但ThingQueue的print函数存在异常,相同位置的节点被识别为nullptr,尽管入队和打印函数遍历队列的逻辑完全一致,仍出现该差异。
最小可复现代码
#include <iostream> using namespace std; struct Thing { int id; Thing() { id = 7; } void print() { cout << "Thing " << to_string(id) << " "; } }; class ThingQueue { public: ThingQueue() { front = nullptr; } void enqueue(const Thing &thing) { cout << "Attempting to enqueue..." << endl; Node *curr = front; while (curr != nullptr) curr = curr->next; curr = new Node; curr->next = nullptr; curr->thing = (Thing*) &thing; cout << "Is curr->thing nullptr? 1 for true, 0 for false: "; cout << to_string(curr->thing == nullptr) << endl; cout << "curr->thing->id = " << to_string(curr->thing->id) << endl; } void print() { cout << "Attempting to print..." << endl; Node *curr = front; cout << "Is curr nullptr? 1 for true, 0 for false: "; cout << to_string(curr == nullptr) << endl; while (curr != nullptr) { curr->thing->print(); curr = curr->next; } } private: struct Node { Node *next; Thing *thing; }; Node *front; }; int main() { Thing *pThing = new Thing(); ThingQueue *pThingQueue = new ThingQueue(); pThingQueue->enqueue(*pThing); pThingQueue->print(); std::cout << std::endl; return 0; }
运行输出
Attempting to enqueue... Is curr->thing nullptr? 1 for true, 0 for false: 0 curr->thing->id = 7 Attempting to print... Is curr nullptr? 1 for true, 0 for false: 1
问题根因
代码存在两处核心错误:
- 新节点未接入队列链表:
enqueue函数中遍历到链表尾部(curr为nullptr)后,直接给局部变量curr分配新节点内存,该操作仅修改了局部指针的指向,既没有更新队列的front指针,也没有将新节点挂载到原有尾节点的next指针上。函数退出后局部变量curr销毁,新节点成为无法访问的泄漏内存,队列的front指针始终保持初始值nullptr,因此打印时直接判定队列为空。 - 存在悬空指针风险:原代码直接存储传入引用参数的地址,若传入的是临时对象,函数退出后对象销毁,存储的指针会成为野指针,引发未定义行为。
修复后完整代码
修复点包含补全链表挂载逻辑、将Node内的Thing成员改为值类型直接拷贝存储对象,示例暂未处理内存释放逻辑:
#include <iostream> using namespace std; struct Thing { int id; Thing() { id = 7; } void print() { cout << "Thing " << to_string(id) << " "; } }; class ThingQueue { public: ThingQueue() { front = nullptr; } void enqueue(const Thing &thing) { if (front == nullptr) { // 队列为空,直接给front分配新节点 front = new Node; front->next = nullptr; front->thing = thing; } else { // 队列非空,遍历找到尾节点 Node* curr = front; while (curr->next != nullptr) curr = curr->next; // 将新节点挂载到尾节点的next指针上 curr->next = new Node; curr->next->next = nullptr; curr->next->thing = thing; } } void print() { Node *curr = front; while (curr != nullptr) { curr->thing.print(); curr = curr->next; } } private: struct Node { Node *next; Thing thing; }; Node *front; }; class Stuff { }; int main() { Thing thing = Thing(); Thing thing2 = Thing(); Thing thing3 = Thing(); ThingQueue tq = ThingQueue(); tq.enqueue(thing); tq.enqueue(thing2); tq.enqueue(thing3); tq.print(); return 0; }
内容的提问来源于stack exchange,提问作者K Man
相关产品推荐
相关产品推荐

