How to save a C ++ object in memory?

What is the life cycle of a C ++ object in an Objective-C class and how to store it in memory?

I tried an opaque structure, create an instance, but this always leads to null.

+4
source share
2 answers

You can create a C ++ object in your Objective-C class by creating a new instance of your C ++ class inside your init method, assigning it to ivar, then in -dealloc call delete in ivar:

 @interface SomeClass : NSObject { SomeCPPClass *cpp_object; } @end @implementation SomeClass - (id) init { self = [super init]; if(self) { cpp_object = new SomeCPPClass(); } return self; } - (void) dealloc { delete cpp_object; [super dealloc]; } @end 
+5
source

If your C ++ object will have the same life cycle as the Objective-C object containing it, you can simply put the C ++ object (and not a pointer to it) in the Objective-C class:

 @interface MyClass { CppObject myObject; } @end 
+1
source

Source: https://habr.com/ru/post/1341173/


All Articles