Cocos2dx memory management, how to use destructors and when to release objects?
c++, cocos2d-x, destructor
Solution
Here is the thing,
Object of the `class Ref` or any class derived from it has a variable `_retainCount` which represents the scope of the object.
Also there is an `autorelease` pool which is similar to the garbage collector in `java`. The object which is added to this `autorelease` pool will be deleted at the end of the frame. Unless its `_retainCount!=0`
Now when you create new object of `Ref` or derived class using the create method it is already added to the `autorelease` pool and you don't need to `release` it or `delete` it anywhere. As you can see in the create function of `Node` below.
Node * Node::create()
{
Node * ret = new (std::nothrow) Node();
if (ret && ret->init())
{
ret->autorelease();
}
else
{
CC_SAFE_DELETE(ret);
}
return ret;
}
But when you create new object using 'new' you definitely need to `delete` it after its use is over. Though it is not recommended to use New to `allocate` the objects of `cocos2d` classes. Rather use create.
Node* temp=Node::create();
then,
temp->retain();
//your work...
temp->release();
or
Node* temp=Node::create();
Node* tempChild=Node::create();
temp->addChild(tempChild);
//your work...
temp->removeFromParent();
Second thing,
when your object is added to the `autorelease` pool but you need to increase its scope you could just retain it , this increments its retain count by one and then you have to manually release it i.e, decrement its retain count after its use is over.
Third Thing,
Whenever you add child your object it is retained automatically but you don't need to `release` it rather you remove it from the parent as mentioned above.
Official documentation is @link below.
[http://www.cocos2d-x.org/wiki/Reference_Count_and_AutoReleasePool_in_Cocos2d-x#Refrelease-retain-and-autorelease][1]
Problem
I'm reading around the web and the documentation but to be honest, I don't get it. Since I'm new to cocos2d-x I would like to understand better how the objects are created/retained and what I'm supposed to do to release them (if required). The thing that confuses me is the usage of smart pointers that I don't know very well. Imagine that in my CCLayer (added to the CCScene) I add a CCSprite, so i do: ``` this->sprite = CCSprite::create("mySprite.png"); this->addChild(sprite); ``` then since I've used create() I'm supposed to release it somewhere? in the destructor of the CCLayer maybe? or I have nothing to do about that? I know the basics of C++ so if I do "new" an object I actually have to delete it in the destructor or when I don't need it anymore, but what about the cocos2dx objects?