目标c中的悬空指针-nil是否还会释放内存? [英] Dangling pointers in objective c - does nil also release memory?

查看:83
本文介绍了目标c中的悬空指针-nil是否还会释放内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解的是:

未释放或释放"内存时发生内存泄漏 当指针未设置为nil且对象被释放时,将发生悬空指针.

Memory leaks occur when memory has not been freed or "released" Dangling pointers occur when the pointer is NOT set to nil AND the object is released.

我的问题是:可以将对象设置为nil释放内存并清除指针引用吗?

my question is: Can setting the object to nil free the memory and clear the pointer reference?

Car *myCar = [[Car alloc] initWithCoolRims: YES];
myCar = nil;
//no mem leaks or dang pointers

或ARC是否这样做:

Car *myCar = [[Car alloc] initWithCoolRims: YES];
[myCar release];    
myCar = nil;
//no mem leaks or dang pointers

谢谢

推荐答案

ARC

对于第一个示例,myCar将设置为nil,新创建的Car将在某个时候释放.这是因为myCar是唯一引用您新创建的Car的东西.

For your first example myCar will be set to nil and the newly created Car will get deallocated at some point. This is because myCar is the only thing that has a reference to your newly created Car.

如果其他东西有很强的指针指向新创建的Car,则只需将nil移出myCar的引用,而其他感兴趣的引用将确定Car实例的生存期

If something else had a strong pointer to the newly created Car then this would simply nil out myCar's reference and the other interested references would determine the lifetime of the Car instance

非ARC

人们仍然这样做吗?

您的第一个示例确实是内存泄漏-您丢失了指向新Car实例的唯一指针,而没有减少alloc的+1引用.

Your first example would indeed be a memory leak - you have lost the only pointer to your new Car instance without decrementing the +1 reference from the alloc.

这篇关于目标c中的悬空指针-nil是否还会释放内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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