指针在删除指针并在 c++ 中再次分配新内存后是否获得相同的内存地址?

Does a pointer get the same memory address after deleting it and allocating new memory again in c++?

本文关键字:内存 指针 是否 地址 c++ 删除 新内存 分配      更新时间:2023-10-16

这是我想澄清的事情。我还有另一个显示链接的功能。调用该显示函数后,我在控制台上得到了一个垃圾值。 但是当我评论"删除临时"语句时,它工作正常,我得到了预期的结果。请帮忙。谢谢。

void MyLinkedList::insertFirst(double data){
    MyLink *temp = new MyLink(data);
    temp->next = first;
    first = temp;
    delete temp;
}

Delete 运算符不是用于删除指针本身,而是用于删除指针指向的内存。

 MyLink *temp = new MyLink(data); //allocate space for a MyLink dataType
 first=tmp; //temp still points to the allocated space
 delete temp; //deallocate the memory space pointed by temp which is the same memory space pointed by first.