Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use ARC when coding in Objective-C++?

I work on a Objective-C++ library project. So far there is only one ObjC object wrapped inside a C++ singleton object in my C++-based codebase. But the client code of the library is likely to use ARC throughout.

There are cases where I need to translate ObjC structures, i.e., structures containing ObjC object members, into their C(++) counterparts.

I read from this post:

http://philjordan.eu/article/mixing-objective-c-c++-and-objective-c++

that:

Even if you use ARC in your project, I recommend you disable it for C++-heavy Objective-C++ files like this one. You can make your C++ code behave itself even with ARC, but it'll often be more work than just putting in the release and retain calls.

The author didn't go in detail of how he reached this conclusion. The post was last updated in 2012. I wonder if there is any significant concern behind this or it is simply outdated info as ObjC evolves.

Thanks!

like image 979
kakyo Avatar asked Apr 19 '26 00:04

kakyo


1 Answers

I've been using c++/objc mixes and arc/no-arc with no problems. The only thing that happens in arc is that objc automagically adds retain/release in most places that uses objc objects. If your c++ class is going to use objc objects, then it also will need to be objc enabled - in that case, arc will just work if it's enabled (and allowed for the file). Otherwise you'll need to retain/release manually. ARC doesn't affect c++ memory management, so there's nothing more to it.

So unless you want to use void* for objc objects and have no objc support in your c++ code, then just follow arc/non-arc rules and it should be fine.

My guess why you might want to have no arc in c++ file is to avoid excessive retain/release calls that arc tends to add sometimes - so basically, if you know where you really need to retain objects (which compiler doesn't know and retains everywhere), so you can get app doing a bit less computations. Also weak references might break things when used in wrong places (like in c++ hashed set or as keys in map, places that might get reallocated), in simple situations they usually work.

like image 151
Rychu Avatar answered Apr 21 '26 14:04

Rychu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!