Game Development Reference
In-Depth Information
The C++ and Cocos2d-x style
In this option, you would instantiate the previous
Player
object as follows:
auto player = new Player();
player->initWithSpriteFrameName("player.png");
this->addChild(player);
player->autorelease();
Player
could do without a static method in this case and the
player
pointer will not ac-
cess the same memory in future as it's set to be autoreleased (so it would not stick around
for long). In this case, however, the memory would not leak. It would still be retained by a
Cocos2d-x list (the
addChild
command takes care of that). You can still access that
memory by going over the children list added to
this
.
If you needed the pointer to be a member property you could use
retain()
instead of
autorelease()
:
m_player = new Player();
m_player->initWithSpriteFrameName("player.png");
this->addChild(m_player);
m_player->retain();
Then sometime later, you would have to release it; otherwise, it will leak:
m_player->release();
Hardcore C++ developers may choose to forget all about the
autorelease
pool and
simply use
new
and
delete
:
Player * player = new Player();
player->initWithSpriteFrameName("player.png");
this->addChild(player);
delete player;//This will crash!
This will not work. You have to use
autorelease
,
retain
, or leave the previous code
without the
delete
command and hope there won't be any leak.