删除后指针本身会发生什么? [英] What happens to the pointer itself after delete?

查看:136
本文介绍了删除后指针本身会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

让我借用操作员删除


取消由ptr指向的内存块(如果不为null),释放
,通过调用操作符$ new
释放之前分配给它的存储空间,并使该指针位置无效。

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.

请帮助我清除我的困惑:删除后指针本身会发生什么?指针本身有一个地址,对吧?因此,在指针块被删除后,指针本身怎么样?

Please help to clear my confusions: what happens to the pointer itself after delete? The pointer itself does have an address, right? So after the pointed block is deleted, what about the pointer itself?

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

Could I say that the pointer itself will be free after returning the method where the pointer is initialized? Is the pointer itself placed on the stack or heap?

推荐答案

指针本身有一个地址和值。执行 delete 后,指针的地址不会改变。分配给指针变量的空间保持在原位,直到程序释放它(它可能永远不会,例如当指针在静态存储区域中时)。标准没有说明指针的值发生了什么变化;它所说的是,你不再允许使用该值,直到你的指针有效的值。这个指针的状态叫做 dangling

The pointer itself does have an address and the value. The address of the pointer does not change after you perform delete on it. The space allocated to the pointer variable itself remains in place until your program releases it (which it might never do, e.g. when the pointer is in the static storage area). The standard does not say what happens to the value of the pointer; all it says is that you are no longer allowed to use that value until you assign your pointer a valid value. This state of the pointer is called dangling.

在程序中,指针 ptr delete 已完成,但在执行 ptr = NULL 之前,之后它变成一个 NULL 指针。

In your program, the pointer ptr is dangling after delete has completed, but before the ptr = NULL assignment is performed. After that it becomes a NULL pointer.


堆栈或堆?

The pointer it self is placed on stack or heap?

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

Pointer variable is a regular variable. Its placement follows the same rules as the placement of other variables, i.e. you can put a pointer in a static area, in an automatic area (commonly known as "the stack") or in the dynamic memory (also known as "the heap"). In this case, you allocate a pointer to a pointer:

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

这篇关于删除后指针本身会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆