2

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.

Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662
Dmitri Nesteruk
  • 23,067
  • 22
  • 97
  • 166

3 Answers3

3

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
  • 68,773
  • 61
  • 187
  • 272
1

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
  • 3,288
  • 20
  • 12
0

In Xcode I am reading "The Objective-C Programming Language", the section titled "Using C++ With Objective-C". I have not tried it, but it says you can use C++ classes as instance variables. It uses the zero argument constructor to initialize any instance variables that are C++ classes. In dealloc the destructors are called in reverse instance variable declaration order.

I just came across OCPtr and a comment on Boost::shared_ptr with Cocoa. Both use a smart reference counting pointer (one that manages all the reference counting for you for assignment etc operators).

Alan Kent
  • 897
  • 1
  • 8
  • 12