gpt4 book ai didi

c++ - 删除后指针本身会发生什么?

转载 作者:行者123 更新时间:2023-12-02 03:05:14 27 4
gpt4 key购买 nike

void doSomething()
{
TheObject *ptr = new TheObject;
delete ptr;
ptr = NULL;
return 0;
}

借用operator delete的话在 cplusplus.com 中:

Deallocates the memory block pointed by ptr (if not null), releasing the storage space previously allocated to it by a call to operator new and rendering that pointer location invalid.

请帮助消除我的困惑:删除后指针本身会发生什么?指针本身确实有一个地址,对吧?那么删除指向的 block 之后,指针本身呢?

我是否可以说,在返回初始化指针的方法后,指针本身将被释放?指针本身是放在栈上还是堆上?

最佳答案

指针本身确实有一个地址和值。对指针执行删除后,指针的地址不会改变。分配给指针变量本身的空间将保持不变,直到您的程序释放它(它可能永远不会这样做,例如,当指针位于静态存储区域时)。该标准没有说明指针的值会发生什么变化;它只是说,在为指针分配有效值之前,您不再被允许使用该值。指针的这种状态称为悬空

在您的程序中,在delete 完成之后、执行ptr = NULL 赋值之前,指针ptr 悬空。之后它就变成NULL指针。

The pointer it self is placed on stack or heap?

指针变量是一个常规变量。它的放置遵循与其他变量的放置相同的规则,即您可以将指针放置在静态区域、自动区域(通常称为“堆栈”)或动态内存(也称为“堆”)中)。在这种情况下,您分配一个指向指针的指针:

TheObject **ptrPtr = new TheObject*; // The pointer to a pointer is on the stack
*ptrPtr = new TheObject; // The pointer to TheObject is in the heap
delete *ptrPtr; // The space for TheObject is released; the space for the pointer to TheObject is not
delete ptrPtr; // Now the space for the pointer to TheObject is released as well
// The space for the pointer to pointer gets released when ptrPtr goes out of scope

关于c++ - 删除后指针本身会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23621677/

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