简体   繁体   中英

Using C++ from Objective C : how to allocate/deallocate?

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.

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 :)

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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM