理解三个函数:release retain autorelease
对应的有两个计数器:ref autoref
autorelease是委托pool管理器在某个时候执行release
话说cocos默认的create方法会创建完成以后立刻、马上执行一次autorelease,行为有点诡异,而且new出来只有ref值是1
作为规范,create以后应该马上autorelease和init否则坑爹
1
2 template
3 xcc::RefPtr TMakeRefPtr()
4 {
5 TVal* pRefTem = new TVal;
6 xcc::RefPtr rpTem = pRefTem;
7 rpTem->init();
8 rpTem->autorelease();
9
10 return rpTem;
11 }
顺便放一个用于cocos的智能指针:
1 // cocos2d 2 template
3 class RefPtr
4 {
5 public:
6 RefPtr(TCocosRefVal* pRefVal = NULL)
7 {
8 m_pRefVal = pRefVal;
9 __IncRef();
10 }
11
12 RefPtr(const RefPtr& refVal)
13 {
14 m_pRefVal = pRefVal;
15 __IncRef();
16 }
17
18 RefPtr(RefPtr&& 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& 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& 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 };