Retaining C++ Objects
C++ and Objective-C do not always mix too well, although the two languages are fully compatible.
With respect to compilation phases, alternating between C, C++, Objective-C and Objective-C++ presents no problem. You just write your software accordingly, freely mixing C, Objective-C, C++ and Objective-C++. Just make sure that the compiler knows what each translation unit contains, normally by source file extension: c for C; cc or cpp or cxx for C++; m for Objective-C; and mm for Objective-C++.
That being specified correctly, your sources compile and link without issues. Only when you start running the code side-by-side however, you might find that memory management can become something of a mishmash. Basic C++ fundamentally has no memory management; I mean nothing automatic. Asking for memory when you want it, freeing memory when you’re done with it: that is all bare C++ gives you. So you typically just roll your own, or find some more-advanced alternative such as Boehm’s garbage collector.
Wouldn’t it be nice however, if you could just simply retain, release and auto-release your C++ objects, just like you do with NSObjects? It would be very nice.
This article outlines a little “trick” for retaining C++ objects on Mac and iPhone. It takes advantage of C++ inheritance; and is simple, so no dependence on internals of CFTypeRef or NSObject. The memory cost is low; just one additional NSObject-derived object per retained C++ object. Final feature, implementation separates from interface by design. Hence you can include retaining within bodies of source without the things being retained having any knowledge of Objective-C. Translation units remain plain old C++, no additional dependencies. The implementation exists apart.
MIT-licensed code provided in full.