2
我希望有人能幫助我解決我的問題,搜索很久並且找不到足夠的答案。我正在使用Objective-C++來合併Objective C和C++類(因爲我的項目需要繼承兩種語言的類)。我的主類是一個Objective-C類,我在C++中有一個小的輔助類,它在Objective-C對象中傳遞並調用它的函數。將自己從Objective C傳遞給C++,不再需要釋放
我的問題是,雖然這工作,沒有釋放(或解構)發生。當我嘗試將Objective-C對象保存到C++對象中的類變量時,似乎將Objective-C類init方法中的self傳遞給C++類會造成某種內存鎖定或泄漏。
我正在使用ARC。
下面是示例代碼:
#import <Foundation/Foundation.h>
@interface MyObjCClass : NSObject
@end
int main(int argc, const char * argv[]) {
MyObjCClass *test = [[MyObjCClass alloc] init];
test = nil;
}
class MyCppClass {
public:
MyCppClass(void *test);
~MyCppClass();
private:
void testFunction();
MyObjCClass *myObjCObject;
};
MyCppClass::MyCppClass(void *test){
MyObjCClass *obj = (__bridge MyObjCClass *) test;
myObjCObject = obj; //when doing this, there is no more deallocation/deconstruction called
NSLog(@"constructing c++ class");
}
MyCppClass::~MyCppClass(){
NSLog(@"deconstructing c++ class");
}
@implementation MyObjCClass {
MyCppClass *myCppObject;
}
- (instancetype)init
{
if (self) {
NSLog(@"initializing ObjC class");
myCppObject = new MyCppClass((__bridge void *) self);
}
return self;
}
- (void)dealloc
{
delete myCppObject;
NSLog(@"deallocating ObjC class");
}
@end