Why retain/release rather than new/delete?
I'm newbie to objective-C, I feel comportable in C++.
My question is: Why language designer of obj-c proper to use retain/release rather then use new/delete(=alloc/dealloc) only?
Maybe my brain is fit to new/delete only memory management, I can not understand why I should manage reference counts, I th开发者_StackOverflowink I know when object have to be alloc/dealloc with my C++ experence.
(Yes, I spend 4 hours to debug reference count problem, it is resolved by 1 line "release")
Can anyone explain me what is better when we use reference counter? (in programming language respects) I think I can manage lifecycle of object by new/delete, but I can't with reference counting.
I need long article that explains why reference counter is useful, if you have link.
P.S: I heard about Compile-time Automatic Reference Counting at WWDC 2011, it is really awesome, it can be reason of use of reference counter, for example.
The short answer is that it is a way to manage object lifetimes without requiring "ownership" as one does with C++.
When creating an object using new
in C++, something has to know when to delete
that object later. Often this is straightforward, but it can be difficult when an object can be passed around and shared by many different "owners" with differing lifetimes.
With reference counting, as long as any other object refers to the object, it stays alive. When all other objects remove their references, it disappears. There are drawbacks to this approach (the debugging of retain/release and reference cycles being the most obvious), but it is a useful alternative to fully automatic garbage collection.
Objective-C is not the only language to use reference counting. In C++, it is common to use std::shared_ptr
, which is the standard reference-counted smart pointer template. Windows Component Object Model programming requires it. Many languages use automated reference-counting behind the scenes as a garbage-collection strategy.
The Wikipedia article is a good place to start looking for more information: http://en.wikipedia.org/wiki/Reference_counting
精彩评论