[Cocos2dx note 014] An object smart pointer template for cocos2dx
Currently, there are countless implementations of C ++ smart pointers. Haha.
This smart pointer is specially tailored for cocos2dx 2.2.x. The main purpose is to make it easy to use and to comply with the existing cocos2dx memory management. This is a smart pointer. You do not need to consider retain or release operations or new or delete operations when using them!
The following is the implementation code
// In many cases, the class members are the sub-objects of CCObject. To ensure normal use of the class and comply with the memory management of cocos2dx, this smart pointer is implemented for ease of use. # Ifndef _ X_COCOS_PTR_H _ # define _ X_COCOS_PTR_H_namespace zdh {template
Class XCocosPtr {public: XCocosPtr (): m_Object (nullptr) {}xcocosptr (T * paramObject): m_Object (paramObject) {if (m_Object! = Nullptr) {m_Object-> retain () ;}} XCocosPtr (const XCocosPtr & paramPtr): m_Object (paramPtr. m_Object) {if (m_Object! = Nullptr) {m_Object-> retain ();}}~ XCocosPtr () {ptr_release () ;}// the xcococosptr & operator = (T * paramObject) {set (paramObject); return * this ;} XCocosPtr & operator = (XCocosPtr & paramObject) {set (paramObject. m_Object); return * this;} // reload the comparison operator bool operator = (T * paramObject) const {return m_Object = paramObject;} bool operator! = (T * paramObject) const {return m_Object! = ParamObject;} // overload * operator T & operator * () {return * m_Object;} const T & operator * () const {return * m_Object ;} // overload-> operator so that it can use T * operator-> () {return m_Object;} const T * operator-> () const {return m_Object;} as a pointer ;} // determine whether the object is empty bool is_null () const {return m_Object = nullptr;} // determine whether the object is empty bool is_not_null () const {return m_Object! = Nullptr;} // create an object here, the create object of the called object is used to create the object T * create () {T * pNewObject = T: create (); set (pNewObject ); return pNewObject;} // set the object void set (T * paramObject) {if (m_Object! = ParamObject) {T * p = m_Object; m_Object = paramObject; if (m_Object! = Nullptr) {m_Object-> retain ();} if (isNotNULL (p) {p-> release () ;}}// get object T * get () {return m_Object;} // The name release is not used here, to prevent confusion with the object's release void ptr_release () {if (m_Object! = Nullptr) {m_Object-> release (); m_Object = nullptr;} private: T * m_Object ;}## endif
Example:
// Data member definition of the class: XCocosPtr
M_Sprite; // m_Sprite = CCSprite: create (""); // or m_Sprite.create () in init ()