cocos2dx引用计数和autorelease

前端之家收集整理的这篇文章主要介绍了cocos2dx引用计数和autorelease前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

cocos2dx实现引用计数


GameObject.h

#ifndef __GameObject_H__
#define __GameObject_H__

class GameObject
{
public:
	GameObject();
	~GameObject();

	int _iCount;

	void myFree();
	
};


#endif



GameObject.cpp

#include "GameObject.h"
#include "cocos2d.h"

USING_NS_CC;
GameObject::GameObject()
{
	_iCount = 1;
}



GameObject::~GameObject()
{

}

void GameObject::myFree()
{
	--_iCount;
	if (_iCount<=0)
	{
		delete this;
	}

	
	log("====shuchu _iCount = %d",_iCount);
}

下面是c++和c语言的申请内存和释放内存的用法示例

cocos2dx实现引用计数


//C++:如果调用delete就一定会去调用析构函数
//如果调用new就一定会去调用构造函数
	GameObject* gameObject = new GameObject();
	gameObject->_iCount = 1;
	delete gameObject; //调用delete就会马上去执行析构函数

	GameObject* gameObject2 = new GameObject[5];
	delete[] gameObject2;
	//new/delete
	//new[]/delete[]


//内存出错
	GameObject* gameObject = new GameObject();
	GameObject* gameObject2 = gameObject;  //引用同一块内存地址
	gameObject->_iCount = 6;
	delete gameObject;

	gameObject2->_iCount = 0;	

//C:malloc和free不执行构造函数和析构函数
	GameObject* gameObject = (GameObject*)malloc(sizeof(GameObject));
	gameObject->_iCount = 0;
	free(gameObject);


//这是实现引用计数
	GameObject* gameObject = new GameObject();
	GameObject* gameObject2 = gameObject;
	gameObject->_iCount+=1;
	gameObject->myFree();
	gameObject->_iCount = 6;

	gameObject2->_iCount = 5;
	gameObject2->myFree();


//autorelease是在析构的时候把所有的指针都赋为null,这样就不会
//导致内存泄露

猜你在找的Cocos2d-x相关文章