android强弱指针

本文详细探讨了Android中的强指针(sp)和弱指针(wp)的使用,以及如何通过extendObjectLifetime来延长对象的生命周期。在RefBase类的基础上,分析了sp和wp如何影响对象的引用计数,并阐述了弱引用升级为强引用的条件及其原理。
摘要由CSDN通过智能技术生成
class MyClass:public RefBase
{
   
public:
	virtual ~MyClass();   //必须要有
	void	func();
}
强指针 sp
sp<MyClass> p_obj; 
p_obj = new MyClass();
p_obj->func();          //可以使用

MyClass* pmyclass;
sp<MyClass> p_obj2=pmyclass;
sp<MyClass> p_obj2(pmyclass); 

弱指针 wp

要想访问弱指针所指向的对象,需升级为强指针, 如果对象已经被销毁,升级的返回值是NULL。

wp<MyClass> weak = new MyClass;
sp<MyClass> strong = weak->promote();
代码分析原理
MyClass* pmyclass = new MyClass();
 {
   
   sp<MyClass> strong(pmyclass);
   wp<MyClass> weak(strong);
    
    //先析构wp,再析构sp
  }
  • RefBase
    所有类的基类, 内部有一个引用类weakref_impl用来统计引用计数
class RefBase
{
   
public:
            void            incStrong(const void* id) const;
            void            decStrong(const void* id) const;
		...
//内部类,weakref_impl的基类
    class weakref_type
    {
   
    public:
        RefBase*            refBase() const;

        void                incWeak(const void* id);
        void                decWeak(const void* id);

        // acquires a strong reference if there is already one.
        bool                attemptIncStrong(const void* id);

        // acquires a weak reference if there is already one.
        // This is not always safe. see ProcessState.cpp and BpBinder.cpp
        // for proper use.
        bool                attemptIncWeak(const void* id);
       ...
       
    };
       ...
            weakref_type*   createWeak(const void* id) const;

            weakref_type*   getWeakRefs() const;



protected:
 ...
    //! Flags for extendObjectLifetime()
    enum {
   
        OBJECT_LIFETIME_STRONG  = 0x0000,
        OBJECT_LIFETIME_WEAK    = 0x0001,
        OBJECT_LIFETIME_MASK    = 0x0001
    };

            void            extendObjectLifetime(int32_t mode);

...
    virtual void            onFirstRef();  //用于子类扩展
    virtual void            onLastStrongRef(const void* id);
    virtual bool            onIncStrongAttempted(uint32_t flags, const void* id);
    virtual void            onLastWeakRef(const void* id);

private:
    friend class weakref_type;
    class weakref_impl;
    ...
private:
...
        weakref_impl* const mRefs;  //reference类用来统计引用计数
};

RefBase::RefBase(
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值