Generally in c++ you have this behaviour:
void foo() {
Object a;
Object *pA = new Object();
(…)
}
This would result in a
being destroyed automatically at function end, as it was allocated on stack. The *pA
would not get destroyed, as it was allocated on the heap (thus, you only loose the reference to it, but the object itself still lives).
Cocos implements a thing called "Automatic Reference Counting" : each CCObject has a reference counter and two methods retain()
and release()
. The way this works is, that every time you create an object, it gets registered in cocos structers (CCPoolManager
). Then with every frame (between them being drawn) there is a maintenance loop which checks the reference counter of all objects : if it is 0
this means (to cocos) that no other objects reference it, so it is safe to delete it. The retain count of an object is automatically incresead when you use this object as an argument for an addChild
function.
Example :
void cocosFoo() {
CCSprite *a = CCSprite::create(…);
CCSprite *b = CCSprite::create(…);
this->addChild(b);
}
What happens here is this :
- Two CCSprites are created, cocos knows about them.
- The
b
sprite is added to this
object (say a CCLayer)
- The function ends, no objects are destroyed (both of them being on heap).
- Somewhere between this and next frame, the maintanance gets run. Cocos chcecks both sprites and sees that
a
has reference count == 0, so it deletes it.
This system is quite good, as you don't need to worry about memory management. If you want to create a CCSprite (for example), but not add it as a child yet, you can call retain()
on it, which will raise its reference counter, saving it from automatic deletion. But then you'd have to remember about calling release()
on it (for example, when adding it as a child).
The general things you have to remeber about are :
- Each call to
retain()
by you needs to be paired with release()
.
- You generally shouldn't delete CCObjects yourself. If you feel that you need to, there is a conveniece macro :
CC_SAFE_DELETE(object)
So to answer your questions in short :
Are there any general guide lines for using retain and release for objects in cocos2d-X ?
Yes, you should generally not need to do it.
When creating objects in a function, is it true that the functions memory is cleaned up the second the function returns.
Answer to this is the whole text above.
When a object is created, calling the retain function of the object, will retain object beyond the function return ?
Yes, as will adding it as a child to another (retained in any way) object.