I'm trying to implement a class from my c++ .h-file together with shared_ptr:s.
Why doesn't my shared_ptr (totPtr) keep its value between the methods?
Example code when I've use a double instead of the class:
#include <memory>
static std::shared_ptr<myCppClass> totPtr;
static double tot;
@implementation ViewController
- (void) createSelf
{
totPtr = std::make_shared<myCppClass>(5);
tot = 10;
}
This method is called after createSelf:
- (void)otherMethod
{
tot += 1; // works, tot = 11
totPtr->doStuff(); // doesn't work, totPtr = nullptr
}
tot2 still has has the value = 0, but tot has the value = 10
For global variables, you should initialized it in
+[initialize], which is a thread-safe way to initialize any global variablesIf you initialize them in
viewDidLoad, it may works now, but when you decide to have multiple instance ofViewController, you will find the second call ofviewDidLoadwill reset these gloabl variables.BUT normally you don't want global variable, you want instance variable / property
which you can initailize them in
viewDidLoadwhich described in the other answer.Note: I don't recommended to use ObjC property with C++ class (i.e.
shared_ptr). Because everytime you access it via property, it require overhead of call a setter/getter method which may need to copyshared_ptr, which is an expansive operation (you should always passshared_ptrby reference in method argument, but this doesn't have good support in ObjC). Access ivar directly allow you to avoid the overhead.