gpt4 book ai didi

c++ - 在 "if"语句中分配的内存,退出时释放

转载 作者:行者123 更新时间:2023-11-30 01:51:15 25 4
gpt4 key购买 nike

我正在输入“if”语句并删除链表中动态分配的节点,然后重新分配它。问题是一旦我退出语句,内存就消失了。相关代码如下:

if (!headByName)                    //if the node is empty,
{
delete headByName; //deallocate the memory that it has been given, and
Node headByName(winery); //reallocate it with the information contained within
//"winery" copied into it
return; //looking at memory, everything works at this point
} // <- this point right here is where the information goes "poof" and disappears

这是 Node 的构造函数:

List::Node::Node(const Winery& winery) :
item(winery.getName(), winery.getLocation(), winery.getAcres(), winery.getRating()),
nextByName(nullptr),
nextByRating(nullptr)
{

}

当我单步执行调试器时,一切都很好地复制到 headByName 中,直到我离开“if”语句。一旦我离开,它就变成了一个空指针。当我删除 return 并转到 else 部分时,也会发生这种情况。我一离开 if 区域,内存就消失了。

最佳答案

您没有在 if 语句中重新分配任何内容。您正在声明一个完全独立的具有相同名称的局部变量 headByName。该局部变量在 block 的末尾被销毁,就像任何其他局部变量一样。

停止尝试声明局部变量。如果你想重新分配你的节点,你应该做类似

的事情
headByName = new Node(winery); 

你说它是一个链表,所以你可能还必须以某种方式将它正确地链接到列表中,但这是你必须自己做的事情。

关于c++ - 在 "if"语句中分配的内存,退出时释放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26331298/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com