经常会在android的framework代码中发现sp<xxx>和wp<xxx>这样的指针,平时看的时候都把他当成一个普通的指针封装过掉了,我们现在就来深入研究一下,我们要知道,sp和wp斗是一个模板类,那么我们就先来看看sp类的定义,这样有助于我们理解sp的含义。
Java代码:
可以看到他确实封转了一个原生指针 T* m_ptr. 再看一下其中一个构造函数和析构函数:
Java代码:
我们一看就应该说好奇怪,因为在构造函数中调用了 incStrong(),在析构函数中调用的 decStrong(),显然是管理引用计数的函数,但是 sp类的中并没有定义这两个函数,这两个函数是在 RefBase类中定义的,由此可以得出结论:
要想使用 sp或者 wp, T必需要继承 RefBase类才行。那么我们来看看效果中给我们呈现的关系。
效果图:
其中 weakref_type是 RefBase的内嵌类, weakref_impl则是 weakref_type的子类, RefBase的大部分工作都是交由 weakref_impl类来完成,通过 RefBase的成员变量 weakref_impl* const mRefs。查看其中一个 sp的构造函数:
Java代码:
可见当一个普通指针变成一个 sp指针后,将会由 RefBase类维护该指针的引用计数,当引用为零时则自动释放该指针指向的内存:
Java代码:
wp是怎么一回事?
wp其实是弱指针的意思, wp类型不能直接对类型T进行操作,要想对T进行某种操作,必需把wp升级为sp指针,使用 promote()来实现升级 :wp weakp= new T();sp t = weakp.promote();wp可能会在弱引用计数不为0的情况下被销毁,执行如下代码:
Java代码:
由此可见虽然 wp的生命周期还没有结束,但是因为升级为 sp后, sp的强引用计数为0,导致 WPTest 被销毁,当强引用为0而弱引用不为0时, WPTest 销毁时,基类 RefBase的 mRefs指向的 weakref_impl类并没有释放,从而保证了弱引用可以继续起作用,这点可以从 RefBase的析构函数中看出来:
Java代码:
不过也可以改变这一行为,我们修改一下 WPTest的构造函数:
Java代码:
这时的打印结果是:
Java代码:
可以看出现在只有当强引用和弱引用的计数都为0时, WPTest对象才会被销毁。
Java代码:
可以看到他确实封转了一个原生指针 T* m_ptr. 再看一下其中一个构造函数和析构函数:
Java代码:
我们一看就应该说好奇怪,因为在构造函数中调用了 incStrong(),在析构函数中调用的 decStrong(),显然是管理引用计数的函数,但是 sp类的中并没有定义这两个函数,这两个函数是在 RefBase类中定义的,由此可以得出结论:
要想使用 sp或者 wp, T必需要继承 RefBase类才行。那么我们来看看效果中给我们呈现的关系。
效果图:
其中 weakref_type是 RefBase的内嵌类, weakref_impl则是 weakref_type的子类, RefBase的大部分工作都是交由 weakref_impl类来完成,通过 RefBase的成员变量 weakref_impl* const mRefs。查看其中一个 sp的构造函数:
Java代码:
可见当一个普通指针变成一个 sp指针后,将会由 RefBase类维护该指针的引用计数,当引用为零时则自动释放该指针指向的内存:
Java代码:
wp是怎么一回事?
wp其实是弱指针的意思, wp类型不能直接对类型T进行操作,要想对T进行某种操作,必需把wp升级为sp指针,使用 promote()来实现升级 :wp weakp= new T();sp t = weakp.promote();wp可能会在弱引用计数不为0的情况下被销毁,执行如下代码:
Java代码:
由此可见虽然 wp的生命周期还没有结束,但是因为升级为 sp后, sp的强引用计数为0,导致 WPTest 被销毁,当强引用为0而弱引用不为0时, WPTest 销毁时,基类 RefBase的 mRefs指向的 weakref_impl类并没有释放,从而保证了弱引用可以继续起作用,这点可以从 RefBase的析构函数中看出来:
Java代码:
不过也可以改变这一行为,我们修改一下 WPTest的构造函数:
Java代码:
这时的打印结果是:
Java代码:
可以看出现在只有当强引用和弱引用的计数都为0时, WPTest对象才会被销毁。