Previous Entry Add to Memories Tell a Friend Next Entry
C++ objects as Objective-C instance variables
[info]chanson
Over on CocoaDev I saw that the CPlusPlusInCocoa page had some out-of-date information on mixing C++ and Objective-C via Objective-C++, so I corrected it.

The particular bit that I want to call out is that, as of Mac OS X 10.4 Tiger, you can have Objective-C instance variables that are direct instances of C++ classes, rather than pointers. The trick is that you have to pass the -fobjc-call-cxx-cdtors flag to the Objective-C++ compiler, via the appropriate build setting in Xcode. (There is a build setting for this, you don't have to put it in the "Other Objective-C++ Flags" build setting or anything like that.)

This will cause the Objective-C runtime to call any zero-argument constructors for C++ objects that are "embedded" when Objective-C classes are allocated, and call any appropriate destructors when those instances are deallocated. Thus you can write code like this:
@interface MyCppStringWrapper : NSMutableString {
    std::string s;
}
@end
And, assuming you've implemented the appropriate class cluster methods for NSString (-characterAtIndex: and -length) and NSMutableString (-replaceCharactersInRange:withString:), it will just work!

The key thing to remember about this is that it requires both the Mac OS X 10.4 version of the Objective-C runtime and GCC 4. You need GCC 4 because that's where the flag is implemented to adjust the code generation, and you need the Mac OS X 10.4 version of the Objective-C runtime because that's where the actual constructor and destructor calling is actually implemented.

One other thing that you need to remember if you try to use this is that (at least as far as I know) it will only invoke zero-argument constructors. So you can't have a complex chain of constructors as an instance variable, such as a std::auto_ptr<T> that wraps another object. But you can still assign to that smart pointer and know that is destructor will be properly called.

XCode Build Setting

(Anonymous)

2007-05-13 06:53 pm (UTC)

OK, very informative, but waht *is* the XCode bulid setting? I searched everywhere and could not find any mention of this in the XCode documentation.

Re: XCode Build Setting

(Anonymous)

2007-05-13 07:51 pm (UTC)

OK, found it burried deep inside the XCode Build Setting Reference:

GCC_OBJC_CALL_CXX_CDTORS (Call C++ Default Ctors/Dtors in Objective-C)

Let's see if this is really useful now... ;)