proper instantiation & memory management in cocos2d-x

ぃ、小莉子 提交于 2019-12-07 07:02:56

问题


I've been looking for documentation for cocos2d-x but it seems to be really really poor beyond the very basics. I understand that my own classes should inherit from CCObject to be able to use (originally cocoa's) retain/release mechanism, but I'm still confused about what happens when you new something. init is not called automatically. is it OK to call it from inside the constructor? does that alone guarantee that my object will start with a reference count of 1? what is CC_SAFE_DELETE and when should I use it? do release and autorelease work exactly like in cocoa? what about CC_SYNTHESIZE? I just need to see a properly coded class example (and it's instantiation/destruction) to understand what I'm supposed to do so as not to screw and leave memory leaks. thank you.


回答1:


If you will look to the code of CCObject class, you will see that in it's constructor reference count is set to 1 there. So, object creation with new is correct. Init is not called because CCObject class has no such a method. Usually I prefer to create objects using 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 macroses like CC_SAFE_DELETE - you can find them in the code of cocos2dx. This macros just check if object is NULL to prevent crash on trying to call release method.




回答2:


The answer provided by Morion is great, I'd just like to add a few useful links about this matter.

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

This forum page also contains some more details and clarifications about it: Memory deallocation in Cocos2d-x

Enjoy coding!



来源:https://stackoverflow.com/questions/10709538/proper-instantiation-memory-management-in-cocos2d-x

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!