Help with memory management in C++

Help with memory management in C++
0.0 0


I’m new to C++ and I would like to know if this is the right way to allocate/deallocate cocoS2d-x objects. Note that I’ve commented image->release(); because I had a linker error about it. Not sure if it’s because I’m not supposed to release an image or if I have a config problem (using cocos2d-x v1 on xCode 4.3).

CCImage *image=new CCImage();
CCTexture2D texture=new CCTexture2D;
pSprite = CCSprite::spriteWithTexture;

// position the sprite on the center of the screen
pSprite~~>setPosition );
// add the sprite as a child to this layer
this~~>addChild(pSprite, 0);


I just wrote a wiki page for your question [[Memory Management in Cocos2d-x]]


Thx. It’s almost identical to what we’re doing on objective c cocos2d iphone.

Should I call image->release(); or not? It makes a linker error Undefined symbols for architecture i386: "cocos2d::CCImage::release()", referenced from:HelloWorld::init() in HelloWorldScene.o


I think that you should have image~~>relese if you are using it like in the example from the first post and I don’t understand why it would not work. Can anyone confirm this? Also I have a question when I should NOT release an object if I create it with new operator? I have something like this:
CCTexture2D texture = new CCTexture2D;
mSprite~~>setTexture; // this will retain texture
And I noticed that this gives me a crash for example when CCImage from mImage is NULL or is to large because initWithImage from CCTexture2D has something like this:
bool CCTexture2D::initWithImage
CCLOG (“cocos2d: CCTexture2D. Can’t create Texture. UIImage is nil”);
return false;
so as we can see texture is being released inside the initWithImage function so I should not release it again becase it will cause a crash. So here is my question: do all init… functions for all cocos2d-x objects work like this? When I call init metod for any cocos2d-x obejct and it returns false then it means that object has been released and I should NOT release it even if I created it with a new operator? Am I right?
I would also like to know when exactly autoreleased object are released? After one program loop with update/draw or when? Will code like this below work perfectly valid?:
texture = new CCTexture2D;
if )
texture~~>autorelease(); // autorelease here before sprite retain will always work properly or not?
mSprite->setTexture(texture); // this will retain texture
// no release or autorelese for texture here becasue if initWithImage returned false then it means that texture has been released automatically

I would appriciate if somebody could explain if mentioned examples are ok.


In case someone also encountered this problem with releasing CCTextere2D after initWithImage failed then I just want to inform that I noticed that this was reported as a bug ( and probably is fixed in cocos2d-2.1rc0-x-2.1.2.