Proper instance and memory management in cocos2d-x

I was looking for documentation for cocos2d-x, but it looks like it is really very poor outside the very core. I understand that my own classes must inherit from CCObject in order to be able to use the (retained) cocaine retain / release mechanism, but I'm still confused about what happens when you new something. init not called automatically. Is it okay to call it from inside the constructor? does this in itself guarantee that my object starts with reference counting 1? What is CC_SAFE_DELETE and when should I use it? do release and autorelease work exactly like cocoa? what about CC_SYNTHESIZE ? I just need to see an example of the class correctly encoded (and its creation / destruction) in order to understand what I should do in order not to blame and not leave memory leaks. thanks.

+4
source share
2 answers

If you look at the code of the CCObject class, you will see that the number of references to the constructor is set to 1. Thus, creating an object using new is correct. Init is not called because the CCObject class does not have such a method. I usually prefer to create objects using a static constructor. Smth like

 MyClass* MyClass::createInstance() { MyClass* object = new MyClass(); // you can create virtual init method // and call it here if( initWasSuccessful ) { object->autorelease(); } else { CC_SAFE_RELEASE_NULL(object); } return object; } 

About all macros like CC_SAFE_DELETE - you can find them in the code cocos2dx. These macros simply check if the object is NULL to prevent a crash when trying to call the release method.

+4
source

The answer provided by Morion is wonderful, I just wanted to add some useful links on this.

Here you can find the official memory management on the Cocos2d-x page: Memory Management in Cocos2d-x

This forum page also contains more detailed information and clarifications in this regard: Freeing up memory in Cocos2d-x

Enjoy the coding!

+1
source

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


All Articles