Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using CREATE_FUNC in Cocos2dx

Tags:

cocos2d-x

Can anyone explain me why do we need to use CREATE_FUNC in Cocos2dx? I saw it in the HelloWorld samples and don't understand it clearly. Please, tell me more detail. Thanks.

like image 459
lolyoshi Avatar asked Mar 03 '14 16:03

lolyoshi


2 Answers

We don't need to use it, it is a helper macro which expands to this :

/**
 * define a create function for a specific type, such as CCLayer
 * @__TYPE__ class type to add create(), such as CCLayer
 */
#define CREATE_FUNC(__TYPE__)
static __TYPE__* create()
{
    __TYPE__ *pRet = new(std::nothrow) __TYPE__();
    if (pRet && pRet->init())
    {
        pRet->autorelease();
        return pRet;
    }
    else
    {
        delete pRet;
        pRet = NULL;
        return NULL;
    }
}

It basically "writes" the create() method for your type, and calls your init() implementation. Its main purpose is to call the autorelease() method, so that you wan't forget about it, if you were to write your own create(). It may not seem as much, but it takes a little of you.

Tip : in most IDEs you can Control + Click (Command on MAC) on pieces of code like functions and macros, and the IDE will take you to it.

Let me know if something is still not clear.

EDIT : Question from comment : For specific, if I want to write a CCCarSprite which extends from CCSprite and have some more functions like run, crash...Do I need to call CREATE_FUNCTION(CCCarSprite)?

No, you don't. What you HAVE to do is call one of superclasses init… methods. This would be best done from your constructor or from your init() in the subclass.

EDIT 2: Second question from comment : Just one more, in the HelloWorld sample in Cocos2dx, why do they need to call CREATE_FUNCTION manually? The don't need to, but it may be considered "good practice" when working with cocos to use their macros, because when they cange something in the create() function implemented by the macro in new version they only need to update it in one place - the macro definition. This leaves less room for error, as there is virtually no chance to "forget" about a place to change the code to new version.

like image 127
Losiowaty Avatar answered Nov 14 '22 04:11

Losiowaty


The more compelling reason to define CREATE_FUNC macro in your function(apart from the memory management) is that, without declaring this, your init() method will never be called.( Check out this piece of code in the macro expansion => if (pRet && pRet->init()))

So this is actually much more than memory management. You can try to put logs in your init method and actually check to verify this.

like image 45
Nanda Kumar Avatar answered Nov 14 '22 02:11

Nanda Kumar