Error

C++博客 首页 新随笔 联系 聚合 管理
  217 Posts :: 61 Stories :: 32 Comments :: 0 Trackbacks
理解三个函数:release  retain  autorelease
对应的有两个计数器:ref  autoref
autorelease是委托pool管理器在某个时候执行release

话说cocos默认的create方法会创建完成以后立刻、马上执行一次autorelease,行为有点诡异,而且new出来只有ref值是1
作为规范,create以后应该马上autorelease和init否则坑爹
 1  
 2 template <typename TVal>
 3 xcc::RefPtr<TVal> TMakeRefPtr()
 4 {
 5     TVal* pRefTem = new TVal;
 6     xcc::RefPtr<TVal> rpTem = pRefTem;
 7     rpTem->init();
 8     rpTem->autorelease();
 9 
10     return rpTem;
11 }

顺便放一个用于cocos的智能指针: 1 // cocos2d
 2 template<typename TCocosRefVal>
 3 class RefPtr
 4 {
 5 public:
 6     RefPtr(TCocosRefVal* pRefVal = NULL)
 7     {
 8         m_pRefVal = pRefVal;
 9         __IncRef();
10     }
11 
12     RefPtr(const RefPtr<TCocosRefVal>& refVal)
13     {
14         m_pRefVal = pRefVal;
15         __IncRef();
16     }
17 
18     RefPtr(RefPtr<TCocosRefVal>&& refVal)
19     {
20         m_pRefVal = refVal.m_pRefVal;
21 
22         refVal.m_pRefVal = NULL;
23     }
24 
25     virtual ~RefPtr()
26     {
27         __DecRef();
28     }
29 
30     virtual const RefPtr& operator = (const RefPtr<TCocosRefVal>& refVal)
31     {
32         if (m_pRefVal != refVal.m_pRefVal)
33         {
34             Reset(refVal.m_pRefVal);
35         }
36 
37         return *this;
38     }
39 
40     virtual void Reset(TCocosRefVal* pRefVal = NULL)
41     {
42         __DecRef();
43         m_pRefVal = pRefVal;
44         __IncRef();
45     }
46 
47     virtual bool operator == (const RefPtr<TCocosRefVal>& refVal)
48     {
49         return (m_pRefVal != refVal.m_pRefVal);
50     }
51 
52     virtual TCocosRefVal* Get() const 
53     {
54         return m_pRefVal;
55     }
56 
57     virtual operator TCocosRefVal*() const
58     {
59         return m_pRefVal;
60     }
61 
62     virtual TCocosRefVal* operator -> () const
63     {
64         return m_pRefVal;
65     }
66 
67     virtual TCocosRefVal& operator * () const
68     {
69         return *m_pRefVal;
70     }
71 
72 protected:
73     void __IncRef()
74     {
75         if (NULL != m_pRefVal)
76         {
77             m_pRefVal->retain();
78         }
79     }
80 
81     void __DecRef()
82     {
83         if (NULL != m_pRefVal)
84         {
85             CCAssert(m_pRefVal->retainCount() >= 1, "");
86             m_pRefVal->release();
87         }
88     }
89 
90 private:
91     TCocosRefVal* m_pRefVal;
92 };
posted on 2015-06-06 21:28 Enic 阅读(155) 评论(0)  编辑 收藏 引用 所属分类: 从零开始写棋牌游戏平台

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理