Hacker News new | ask | show | jobs
by vasi 5599 days ago
Reference-counting in Objective-C is probably an improvement compared to the very basic memory management of C++. (C++ fans, yes, RAII is better than nothing, but no, it's not enough.) But ref-counting is also a far cry from the tracing garbage collectors most of us expect in a modern language.

There are plenty of gotchas in non-GC'ed Obj-C memory management, see my previous comment in a different thread: http://news.ycombinator.com/item?id=1986799 . Also, the interaction of ref-counting with multi-threading is just awful: objects that some code uses but doesn't own must be obsessively retained-and-autoreleased in case another thread preempts and releases them. Behind the scenes, this takes and releases a lock on the object, which doesn't exactly help efficiency.

I'd rather hear about more of the things that Objective-C really gets right, instead of another "omg, I'd never heard of ref-counting before!" post. Here's a couple to start people off:

* Using named messages (instead of vtables a la C++) provides quite good introspection and run-time modification of the class hierarchy. This allows cool features like "delegates" that implement a subset of extension behaviours, and method forwarding.

* Objective-C's "informal protocols" are what we'd now call duck-typing.

1 comments

Reference counting is available in C++ through the use of smart pointers ( ex. boost::shared_ptr ). In fact unlike Objective C there is no need to explicitly increment/decrement the reference count.
Yes, but the problem is that it's just one approach out of many, so when using other libraries and APIs, you have no consistency. (For example, you'll have to wrap their classes in your refcounting scheme, and unwrap when passing them back in.)
You can also just make your own CSmartObject base class (which does reference counting), and just have all of your objects inherit from that.

Reference counting may not be built into C++ itself, but it's not super difficult to add in either.