Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destructor in Objective-C++

I have an objective-C++ class which contain some honest C++ object pointers.

When the Obj-C++ class is destroyed does it call dealloc immediately? If so, then is the best way to destroy the C++ class by putting

delete obj

in the dealloc method?

like image 889
John Smith Avatar asked Jun 28 '10 20:06

John Smith


2 Answers

I presume when you say "Obj-C++ class" you mean an Objective-C class that happens to contain some C++ classes.

Objective-C classes don't call dealloc when they're destroyed; they're destroyed by having the dealloc message sent to them.

With that bit of pedantry out the way, if your init method instantiates obj then, yes, call delete obj in the dealloc:

-(void)dealloc {
  delete obj;
  [super dealloc];
}
like image 119
Frank Shearar Avatar answered Sep 20 '22 19:09

Frank Shearar


As a supplement to Frank Shearar's correct answer, provided you are using the OSX 10.4 or later SDK (and you probably are; though I'm not sure about the iPhone runtime here) you can also include C++ members of Objective-C classes, i.e. without resorting to a pointer. The problem in earlier versions of the OSX SDK was that the constructor and destructor of the C++ member simply would not get called. However, by specifying the fobjc-call-cxx-cdtors compiler option (in XCode it is exposed as the setting GCC_OBJC_CALL_CXX_CDTORS), the ctor and dtor will get called. See also Apple docs, a bit down that page.

like image 29
harms Avatar answered Sep 20 '22 19:09

harms