语句内分配"if"内存,退出时解除分配

Memory allocated within "if" statement, deallocated upon exit

本文关键字:退出 解除分配 if 分配 语句 内存      更新时间:2023-10-16

我正在输入一个"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相同。该局部变量在块的末尾被销毁,就像任何其他局部变量一样。

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

headByName = new Node(winery); 

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

您的变量是在if作用域内创建的,因此在作用域末尾被删除。以与相同的方式

void foo()
{
   int b;
   while ()
   {
    int a;
   }
}

b在foo()范围内是可访问的,a在while的foo范围内是可以访问的,并且它们都不能在foo()之外访问。