简体   繁体   English

Objective-C ++中的析构函数

[英]Destructor in Objective-C++

I have an objective-C++ class which contain some honest C++ object pointers. 我有一个Objective-C ++类,它包含一些诚实的C ++对象指针。

When the Obj-C++ class is destroyed does it call dealloc immediately? 当Obj-C ++类被销毁时,它会立即调用dealloc吗? If so, then is the best way to destroy the C++ class by putting 如果是这样,那么通过put来破坏C ++类是最好的方法

delete obj

in the dealloc method? 在dealloc方法?

I presume when you say "Obj-C++ class" you mean an Objective-C class that happens to contain some C++ classes. 我假设当你说“Obj-C ++类”时,你的意思是一个恰好包含一些C ++类的Objective-C类。

Objective-C classes don't call dealloc when they're destroyed; Objective-C类在被销毁时不会调用dealloc; they're destroyed by having the dealloc message sent to them. 通过发送dealloc消息来销毁它们。

With that bit of pedantry out the way, if your init method instantiates obj then, yes, call delete obj in the dealloc: 如果你的init方法实例化了obj,那么,在dealloc中调用delete obj

-(void)dealloc {
  delete obj;
  [super dealloc];
}

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, ie without resorting to a pointer. 作为Frank Shearar正确答案的补充,只要你使用的是OSX 10.4或更高版本的SDK(你可能就是这样;虽然我不确定这里的iPhone运行时),你也可以包含Objective-C类的C ++成员,即没有诉诸指针。 The problem in earlier versions of the OSX SDK was that the constructor and destructor of the C++ member simply would not get called. 早期版本的OSX SDK中的问题是C ++成员的构造函数和析构函数根本不会被调用。 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. 但是,通过指定fobjc-call-cxx-cdtors编译器选项(在XCode中,它将作为设置GCC_OBJC_CALL_CXX_CDTORS公开),ctor和dtor将被调用。 See also Apple docs , a bit down that page. 另请参阅Apple文档 ,在该页面下方。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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