目标c中的悬空指针-nil是否还会释放内存? [英] Dangling pointers in objective c - does nil also release memory?
问题描述
我了解的是:
未释放或释放"内存时发生内存泄漏 当指针未设置为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屋!