NULL指针与解除分配相同吗? [英] NULL pointer is the same as deallocating it?

查看:117
本文介绍了NULL指针与解除分配相同吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一段代码,我被一个疑问攻击:如果我为该指针分配NULL,那么分配给指针的内存会发生什么?

I was working on a piece of code and I was attacked by a doubt: What happens to the memory allocated to a pointer if I assign NULL to that pointer?

例如:

A = new MyClass();

{...do something in the meantime...}

A = NULL;

空间仍然分配,但没有引用。

The space is still allocated, but there is no reference to it. Will that space be freed later on, will it be reused, will it remain on stack, or what?

推荐答案

A = new MyClass();

{...do something in the meantime...}

A = NULL;

我跟踪它的方式是有两个单独的对象。 中, MyClass 实例由 new 分配。在堆栈上,有一个名为 A 的指针。

The way I keep track of it is that there are two separate objects. Somewhere on the heap, a MyClass instance is allocated by new. And on the stack, there is a pointer named A.

A 只是一个指针,没有什么神奇的out,它没有一些特殊的连接到堆分配 MyClass 对象。现在只是指向那个,但是可以改变。

A is just a pointer, there is nothing magical about out, and it doesn't have some special connection to the heap-allocated MyClass object. It just happens to point to that right now, but that can change.

在最后一行,这是发生了什么。你改变指针指向别的东西。这不会影响其他对象。它不影响它用来指向的对象,它不会影响它被设置为指向现在的对象(如果有的话)。再次, A 只是一个愚蠢的原始指针像任何其他。它可能为NULL,或者它可能指向堆栈上的一个对象,或者可能指向堆上的一个对象,或者它可能未初始化并指向随机垃圾。但这就是它的全部。它指出,它不以任何方式取得对它指向的对象的所有权或修改。

And on the last line, that is exactly what happens. You change the pointer to point to something else. That doesn't affect other objects. It doesn't affect the object it used to point to, and it doesn't affect the object (if any) that it is set to point to now. Again, A is just a dumb raw pointer like any other. It might be NULL, or it might point to an object on the stack, or it might point to an object on the heap, or it might be uninitialized and point to random garbage. But that's all it does. It points, it doesn't in any way take ownership of, or modify, the object it points to.

这篇关于NULL指针与解除分配相同吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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