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.![[info]](http://l-stat.livejournal.com/img/userinfo.gif)
XCode Build Setting
(Anonymous)
2007-05-13 06:53 pm (UTC)