Hi,
I wrote tool for working with pointers on Cocos2d-x objects.
#ifndef CCPtr_h
#define CCPtr_h
#include <type_traits>
#include "cocos2d.h"
template < class T,
class = typename std::enable_if<std::is_base_of<cocos2d::Ref, T>::value>::type
>
class CCPtr {
cocos2d::Ref *m_ptr = nullptr;
public:
CCPtr() {}
CCPtr(T *obj) {
if (m_ptr) {
m_ptr->release();
}
m_ptr = obj;
m_ptr->retain();
}
CCPtr(CCPtr<T> &obj) {
if (m_ptr) {
m_ptr->release();
}
m_ptr = obj.m_ptr;
m_ptr->retain();
}
CCPtr(CCPtr<T>&& obj) {
m_ptr = obj.m_ptr;
obj.m_ptr = nullptr;
}
void operator=(T *obj) {
if (m_ptr) {
m_ptr->release();
}
m_ptr = obj;
m_ptr->retain();
}
void operator=(CCPtr<T> &obj) {
if (m_ptr) {
m_ptr->release();
}
m_ptr = obj.m_ptr;
m_ptr->retain();
}
void operator=(CCPtr<T>&& obj) {
m_ptr = obj.m_ptr;
obj.m_ptr = nullptr;
}
~CCPtr() {
if (m_ptr) {
m_ptr->release();
}
m_ptr = nullptr;
}
T* get () const { return static_cast<T*>(m_ptr); }
T* operator->() const { return static_cast<T*>(m_ptr); }
};
#endif /* CCPtr_h */
You no longer have to take care of the call retain() and release().
What do you think about it?
Oh. The cocos already has this class. Fail!