cocos2d-x中的 实例化与内存管理

来源:互联网 发布:优化电脑配置的软件 编辑:程序博客网 时间:2024/06/11 22:54

在 cocos2d-x by example beginner's guide,第2章,P23页中(翻译请凑合看)


  There is no Automatic Reference Counting (ARC) in cocos2d-x, so Objective-C developers
who have forgotten memory management might have a problem here.

由于在cocos2d-x中没有采用ARC机制,所以Objective-C开发者可能会因为忘记内存管理引起一些问题。


  The rule regarding memory management with C++ is very simple: if you new, you must
delete. Cocos2d-x, however, will add a few other options and commands, similar to the
ones we have in Objective-C (without ARC). That is because Cocos2d-x, unlike C++, and
very much like Objective-C, has a root class. The framework is more than just a C++ port
of Cocos2d. It also ports certain notions of Objective-C to C++, in order to recreate its
memory management system.
C++中的内存管理准则非常简单:如果你调用了 new,那么你一定别忘了delete。但是通过在cocos2d-x中,
添加了一些扩展的特性和命令,使得其像没有引用ARC的Objective-C。cocos2d-x并不像C++那样,反倒是和Objective-C很像,都有一个根类.
(ps:后面的翻译拿不准)cocos2d-x,不仅是cocos2d的一个分支,它更是一个用C++代替Objective-C中部分特性,再创了一套内存管理系统。


  Cocos2d-x has a CCObject class which is the root of every major object in the framework.

It allows the framework to have autorelease pools, and retain counts, as well other
Objective-C equivalents.
CCObject 是cocos2d-x构架的中绝大部分类的根类,它框架有了与Objective-C一样的 autorelease pool(自动释放池), retain counts(引用计数)。
Player::Player () {this->setPosition ( ccp(0,0) );}Player * Player::create () {Player * player = new Player();if (player && player->initWithSpriteFrameName("player.png")) {player->autorelease();return player;}CC_SAFE_DELETE(player);return NULL;}

When instantiating Cocos2d-x objects you basically have two options.

我们有两种方式来实例化cocos2d-x中的对象。


Option 1 – use static methods

第一种方法:用静态方法


  This is the recommended way. The three-stage instantiation process of Objective-C, with
alloc, init, and autorelease/retain is recreated here. So for instance a Player class,
which extends CCSprite, might have the following methods:
  我推荐这种方法。在Objective-C实例化,分“三步走” 1.alloc, 2. init, 3.autorelease/retain.
例如:实例化一个CCSprite的子类Player类的对象,通常需要以下几步:

  For instantiation, you call the static create method. It will create a new Player objectas an empty husk version of Player. No major initialization should happen inside theconstructor, just in case you may have to delete the object due to some failure in theinstantiation process. Cocos2d-x has a series of macros for object deletion and release,like the CC_SAFE_DELETE used previously.
  我们可以调用静态的create方法,来实例化一个对象。create会创建Player类一个空的对象,该对象并没有在构造函数中进行有效的初始化,所以在实例化失败的时候,我们应该用delete,删除它。cocos2d-x中,为了对象方便进行 删除和释放操作而准备了一系列的宏,比如前面用到的CC_SAFE_DELETE。


未完待续
原创粉丝点击