Dangling pointers in objective c - does nil also release memory?

后端 未结 2 1052
春和景丽
春和景丽 2021-01-12 04:19

What I understand is:

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

相关标签:
2条回答
  • 2021-01-12 04:43

    Under ARC

    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.

    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

    Under Non-ARC

    People still do this?

    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.

    0 讨论(0)
  • 2021-01-12 04:49

    You do the first, ARC does the equivalent of the second. There are no dangling references, with or without the nil assignment, since ARC retained the referenced object (retain count 1) and when execution moves beyond the scope of the myCar definition, ARC will guarantee a release of myCar's referenced object, decrementing the reference count and deallocating the object memory if the resulting reference count is 0.

    0 讨论(0)
提交回复
热议问题