cocos2dx实现引用计数
GameObject.h
#ifndef __GameObject_H__#define __GameObject_H__class GameObject{public: GameObject(); ~GameObject(); int _iCount; voID myFree(); };#endif
#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,这样就不会//导致内存泄露总结
以上是内存溢出为你收集整理的cocos2dx引用计数和autorelease全部内容,希望文章能够帮你解决cocos2dx引用计数和autorelease所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)