Memory management in cocos2d-x c++

  • makalele
    Likes 1

    Problem Description

    Hi,

    I’m wondering about how exactly garbage collecting is handled by cocos2d-x. I’ve already read about autorelease and I understand how reference count works. If I’ll create for example sprite and if I won’t add it on the scene it’ll be released immediately (retain() is an option to fix situation like this). But what about standard c++ types? Like I’ve got HelloWorldScene and have for example array int* foo (in HelloWorldScene::init I call ‘foo = new int[5]’ for example to allocate memory). If I’ll switch scene (so old one should be destroyed) will it be released as well? Or I should implement onExit() and there call ‘delete foo’?. How about vector? What about custom classes? Can I just extend cocos2d::Ref and use CREATE_FUNC macro? Is it good practice?

    Regards

  • Sonar Systems admin
    Likes 0

    Hello

     

    Check this link out which covers memory management very well. To put it simple Cocos2d-x handles most of the Cocos stuff but regular C++ you release how you would normally with C++. Hope this helps.

     

    http://discuss.cocos2d-x.org/t/memory-deallocation-in-cocos2d-x/137

  • makalele
    Likes 1

    Ok I mostly understand memory management. But still few are unclear to me.

    What about std::vector? I’ve read somewhere it’s automatically calling destructors of all objects when cleared. 

    For example:

    std::vector<std::string> strings;

    Should I just leave it?

    What about this:

    std::vector<std::string> *strings = new std::vector<std::string>();

    I’m also curious what’s special about Vector class from cocos2d-x. It does not seem significally differ from std::vector. push_back is pushBack, erase requies index – not iterator.

  • Sonar Systems admin
    Likes 0

    Best to use Cocos2d-x Vectors if you can as they handle memory management all for you.

  • makalele
    Likes 1

    I see now.. Thanks for answer. But cocos2d::Vector has one limitation: you can’t use it on objects that aren’t extending cocos2d::Ref. So for example:

     

    std::vector<std::string> *strings = new std::vector<std::string>();

     

    in scene destructor:

    strings->clear();

    delete strings;

     

    Is it ok?

  • Sonar Systems admin
    Likes 1

    Check out this page for more information

     

    http://www.cplusplus.com/reference/vector/vector/clear/

  • makalele
    Likes 1

    Great. Thanks for help! (as always).

Login to reply