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(