本文共 9035 字,大约阅读时间需要 30 分钟。
LightRefBase类: 用于对象引用计数。
templateclass LightRefBase { public: inline LightRefBase() : mCount(0) { } inline void incStrong(__attribute__((unused)) const void* id) const { __sync_fetch_and_add(&mCount, 1); } inline void decStrong(__attribute__((unused)) const void* id) const { if (__sync_fetch_and_sub(&mCount, 1) == 1) { delete static_cast (this); } } //! DEBUGGING ONLY: Get current strong ref count. inline int32_t getStrongCount() const { return mCount; } typedef LightRefBase basetype; protected: inline ~LightRefBase() { } private: friend class ReferenceMover; inline static void moveReferences(void*, void const*, size_t, const ReferenceConverterBase&) { } private: mutable volatile int32_t mCount; };
继承于LightRefBase,有了person属性,有sp类的father和son两个成员。
class Person : public LightRefBase{ private: sp father; sp son; public: Person() { cout <<"Pserson()"< &father) { this->father = father; } void setSon(sp &son) { this->son = son; } .... }
sp类包含person类的m_ptr (T=person)
templateclass sp { public: inline sp() : m_ptr(0) { } private: ........... T* m_ptr; }
spfather = new Person(); /* 1. 对于 new Person() * 1.1 Person对象里的father先被构造 * 1.2 Person对象里的son被构造 * 1.3 Person对象本身 * /
SPfather= new Person();会导致析构函数执行template sp ::sp(T* other) : m_ptr(other) { if (other) other->incStrong(this); }
void setSon(sp&son) { this->son = son; }
运算符=,被重载
public: inline sp() : m_ptr(0) { } sp(T* other); sp(const sp& other); template sp(U* other); template sp(const sp & other); ~sp(); // Assignment sp& operator = (T* other); .... } template sp ::sp(T* other) : m_ptr(other) { if (other) other->incStrong(this); }
对于运算符,右值是传的参数,左值是返回值。
spson = new Person(); father->setSon(son); //fathter->被重载后,就是father中m_ptr,示意图中的person类对象p1 void setSon(sp &son) { this->son = son; //this指的是p1->son //因为p1->son是sp类,sp类的"="被重载 //“=”的右值是son,左值是p1->son } template sp & sp ::operator = (const sp & other) { // other = son cout<<"tom operator= 1"< incStrong(this); } // this是p1->son,因为p1->son中的m_ptr是空的。 if (m_ptr) { m_ptr->decStrong(this); } //p1->son.m_ptr = p2 m_ptr = otherPtr; return *this; }
templatesp ::~sp() { if (m_ptr) m_ptr->decStrong(this); }
所以在test_func函数中,在father对象,执行析构,则会减少对应的p1对象mCount,mCount=1; 无法释放。
同理,销毁son对象,执行析构,会减少对应的p2对象中的mCount,则mCount=1,无法释放。原因:
在设置father的person对象p1中的son指向p2,把p2的引用值加1.就是强引用。转载地址:http://safab.baihongyu.com/