利用智能指针将非cocos2d-x对象转化为cocos2d-x对象

 - by Hector

先看代码

 

template <class T>
class WRef:public Ref
{
public:
    WRef(T* p):_p(p){};
    virtual ~WRef(){delete _p;};
    
    static WRef* Create(T* p){
        WRef* pRet = new WRef(p);
        if (pRet)
        {
            pRet->autorelease();
            return pRet;
        }
        else
        {
            delete pRet;
            pRet = NULL;
            return NULL;
        }
    };
    
    inline T* operator->() const throw() {return _p;}
    inline T* get(){return _p;};
protected:
    T* _p;
};

cocos2d-x对象都是继承自Ref这个类,拥有引用计数,并可以由自动释放池自动释放,如果非cocos2d-x类,比如你自己写的一些类,STL容器等想将其生命周期绑定到某个Node上,就没法实现了。

还有一个重要的作用是cocos的一些回调参数必须继承自Ref,想传入非Ref参数就没办法了。

利用智能指针的思想,将非cocos2d-x类封装到Ref里面,使用起来也比较简单。
比如:

//创建:
btns =new std::vector<Widget*>;
            _wgt->setUserObject(WRef<std::vector<Widget*>>::Create(btns));
//使用
auto btns = ((WRef<std::vector<Widget*>>*)_wgtPapers->getUserObject())->get();

Leave a comment