強指標和弱指標基礎
android中的智能指標包括:輕量級指標、強指標、弱指標,
強指標:它主要是通過強參考計數來進行維護物件的生命周期,
弱指標:它主要是通過弱參考計數來進行維護所指向物件的生命周期,
如果在一個類中使用了強指標或者弱指標的技術,那么這個類就必須從RefBase這個類進行做繼承,因為強指標和弱指標是通過RefBase這個類來提供實作的參考計數器,
強指標和弱指標關系相對于輕量級指標來說更加親密,因此他們一般是相互配合使用的,
強指標原理分析
以下針對原始碼的分析都是來源于android5.0系統原始碼
強指標的定義實作主要在\frameworks\rs\cpp\util\RefBase.h檔案中
class RefBase
{
public:
//定義了成員變數用于維護強參考物件的參考計數
void incStrong(const void* id) const;
//定義了成員變數用于維護強參考物件的參考計數
void decStrong(const void* id) const;
void forceIncStrong(const void* id) const;
//獲取強指標計數的數量.
int32_t getStrongCount() const;
//這個類主要實作計數器的
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);
//! DEBUGGING ONLY: Get current weak ref count.
int32_t getWeakCount() const;
//! DEBUGGING ONLY: Print references held on object.
void printRefs() const;
//! DEBUGGING ONLY: Enable tracking for this object.
// enable -- enable/disable tracking
// retain -- when tracking is enable, if true, then we save a stack trace
// for each reference and dereference; when retain == false, we
// match up references and dereferences and keep only the
// outstanding ones.
void trackMe(bool enable, bool retain);
};
weakref_type* createWeak(const void* id) const;
weakref_type* getWeakRefs() const;
//! DEBUGGING ONLY: Print references held on object.
inline void printRefs() const { getWeakRefs()->printRefs(); }
//! DEBUGGING ONLY: Enable tracking of object.
inline void trackMe(bool enable, bool retain)
{
getWeakRefs()->trackMe(enable, retain);
}
typedef RefBase basetype;
protected:
RefBase();
virtual ~RefBase();
//! Flags for extendObjectLifetime()
enum {
OBJECT_LIFETIME_STRONG = 0x0000,
OBJECT_LIFETIME_WEAK = 0x0001,
OBJECT_LIFETIME_MASK = 0x0001
};
void extendObjectLifetime(int32_t mode);
//! Flags for onIncStrongAttempted()
enum {
FIRST_INC_STRONG = 0x0001
};
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 ReferenceMover;
static void moveReferences(void* d, void const* s, size_t n,
const ReferenceConverterBase& caster);
private:
friend class weakref_type;
//通過類物件來獲取計數器資料,
class weakref_impl;
RefBase(const RefBase& o);
RefBase& operator=(const RefBase& o);
weakref_impl* const mRefs;
};
通過以上類定義可以看到 RefBase類里面嵌套著weakref_type類,這個weakref_type類也的物件mRefs來描述物件的參考計數,也就是說每一個RefBase物件都包含一個weakref_type物件,
virtual表示的是虛函式,friend表示友元函式,
總結
如果一個物件的生命周期控制標志值被設定為0的情況下,只要它的強參考計數值也為0,那么系統就會自動釋放這個物件,
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/306010.html
標籤:其他
