views:

1416

answers:

3

Currently, my Objective C classes use C++ objects by doing a new when the owner is created, and calling delete when it is destroyed. But is there another way? I'd like to be able to declare, say, an auto_ptr whose scope lasts the duration of the Objective C class' lifetime.

+3  A: 

Ok, let me assume you are using C++ and Objective-C on a Mac, if I'm right you are likely using X-code. So if you go to the properties (info) of your project. You can check the compile options (GCC's). In there, there is an option to enable C++ constructors/destructors (which is turned off by default in Cocoa projects).

Then you get default-like C++ scoping, however I haven't used it much and I've had problems with heavily template code (Boost).

Also I don't think anyone officially supports this besides some good souls working on GCC. So I'd recommend that you unit test anything like this, and keep note that anything could go wrong.

Nevertheless being able to use C++ in objective-C, for me as a C++ person, is a relief and the risks are worth the benefits :)

Robert Gould
+1  A: 

If you have even the slightest hope of retaining what little sanity that we as developers have left you won't do that. It is best to delete your C++ objects. In general, while it is safe to mix Objective-C and C++ on a line-by-line basis, do not expect the runtime to support doing something fancy like mixing lifetimes. In general, you can safely destroy your objects when your obj-c class's dealloc is called but other than that, do not expect to mix class scope and not cry.

wisequark
A: 

Hello everyone, I am having same issue and need help. I am writing a game engine for iPhone. Some of the module is written in C++, while the core classes are in Objective-C.

Now if I instantiate an Objective-C object in C++ class, I would like to alloc it in C++ constructor and dealloc it in C++ desctructor. Now what would be teh best way to do it?

Can anyone explain the issues around C++ constructor and desctructor while mixing C++ in objective C code?

Thanks a lot in advance!

pixelord