Android系統的運行時庫層代碼是用C++來編寫的,用C++來寫代碼最容易出錯的地方就是指針了,一旦使用不當,輕則造成內存泄漏,重則造成系統崩潰。不過系統爲我們提供了智能指針,避免出現上述問題,本文將系統地分析Android系統智能指針(輕量級指針、強指針和弱指針)的實現原理。
在使用C++來編寫代碼的過程中,指針使用不當造成內存泄漏一般就是因爲new了一個對象並且使用完之後,忘記了delete這個對象,而造成系統崩潰一般就是因爲一個地方delete了這個對象之後,其它地方還在繼續使原來指向這個對象的指針。爲了避免出現上述問題,一般的做法就是使用引用計數的方法,每當有一個指針指向了一個new出來的對象時,就對這個對象的引用計數增加1,每當有一個指針不再使用這個對象時,就對這個對象的引用計數減少1,每次減1之後,如果發現引用計數值爲0時,那麼,就要delete這個對象了,這樣就避免了忘記delete對象或者這個對象被delete之後其它地方還在使用的問題了。但是,如何實現這個對象的引用計數呢?肯定不是由開發人員來手動地維護了,要開發人員時刻記住什麼時候該對這個對象的引用計數加1,什麼時候該對這個對象的引用計數減1,一來是不方便開發,二來是不可靠,一不小心哪裏多加了一個1或者多減了一個1,就會造成災難性的後果。這時候,智能指針就粉墨登場了。首先,智能指針是一個對象,不過這個對象代表的是另外一個真實使用的對象,當智能指針指向實際對象的時候,就是智能指針對象創建的時候,當智能指針不再指向實際對象的時候,就是智能指針對象銷燬的時候,我們知道,在C++中,對象的創建和銷燬時會分別自動地調用對象的構造函數和析構函數,這樣,負責對真實對象的引用計數加1和減1的工作就落實到智能指針對象的構造函數和析構函數的身上了,這也是爲什麼稱這個指針對象爲智能指針的原因。
在計算機科學領域中,提供垃圾收集(Garbage Collection)功能的系統框架,即提供對象託管功能的系統框架,例如Java應用程序框架,也是採用上述的引用計數技術方案來實現的,然而,簡單的引用計數技術不能處理系統中對象間循環引用的情況。考慮這樣的一個場景,系統中有兩個對象A和B,在對象A的內部引用了對象B,而在對象B的內部也引用了對象A。當兩個對象A和B都不再使用時,垃圾收集系統會發現無法回收這兩個對象的所佔據的內存的,因爲系統一次只能收集一個對象,而無論系統決定要收回對象A還是要收回對象B時,都會發現這個對象被其它的對象所引用,因而就都回收不了,這樣就造成了內存泄漏。這樣,就要採取另外的一種引用計數技術了,即對象的引用計數同時存在強引用和弱引用兩種計數,例如,Apple公司提出的Cocoa框架,當父對象要引用子對象時,就對子對象使用強引用計數技術,而當子對象要引用父對象時,就對父對象使用弱引用計數技術,而當垃圾收集系統執行對象回收工作時,只要發現對象的強引用計數爲0,而不管它的弱引用計數是否爲0,都可以回收這個對象,但是,如果我們只對一個對象持有弱引用計數,當我們要使用這個對象時,就不直接使用了,必須要把這個弱引用升級成爲強引用時,才能使用這個對象,在轉換的過程中,如果對象已經不存在,那麼轉換就失敗了,這時候就說明這個對象已經被銷燬了,不能再使用了。
瞭解了這些背景知識後,我們就可以進一步學習Android系統的智能指針的實現原理了。Android系統提供了強大的智能指針技術供我們使用,這些智能指針實現方案既包括簡單的引用計數技術,也包括了複雜的引用計數技術,即對象既有強引用計數,也有弱引用計數,對應地,這三種智能指針分別就稱爲輕量級指針(Light Pointer)、強指針(Strong Pointer)和弱指針(Weak Pointer)。無論是輕量級指針,還是強指針和弱指針,它們的實現框架都是一致的,即由對象本身來提供引用計數器,但是它不會去維護這個引用計數器的值,而是由智能指針來維護,就好比是對象提供素材,但是具體怎麼去使用這些素材,就交給智能指針來處理了。由於不管是什麼類型的對象,它都需要提供引用計數器這個素材,在C++中,我們就可以把這個引用計數器素材定義爲一個公共類,這個類只有一個成員變量,那就是引用計數成員變量,其它提供智能指針引用的對象,都必須從這個公共類繼承下來,這樣,這些不同的對象就天然地提供了引用計數器給智能指針使用了。總的來說就是我們在實現智能指會的過程中,第一是要定義一個負責提供引用計數器的公共類,第二是我們要實現相應的智能指針對象類,後面我們會看到這種方案是怎麼樣實現的。
接下來,我們就先介紹輕量級指針的實現原理,然後再接着介紹強指針和弱指針的實現原理。
1. 輕量級指針
先來看一下實現引用計數的類LightRefBase,它定義在frameworks/base/include/utils/RefBase.h文件中:
- template <class T>
- class LightRefBase
- {
- public:
- inline LightRefBase() : mCount(0) { }
- inline void incStrong(const void* id) const {
- android_atomic_inc(&mCount);
- }
- inline void decStrong(const void* id) const {
- if (android_atomic_dec(&mCount) == 1) {
- delete static_cast<const T*>(this);
- }
- }
- //! DEBUGGING ONLY: Get current strong ref count.
- inline int32_t getStrongCount() const {
- return mCount;
- }
- protected:
- inline ~LightRefBase() { }
- private:
- mutable volatile int32_t mCount;
- };
前面說過,要實現自動引用計數,除了要有提供引用計數器的基類外,還需要有智能指針類。在Android系統中,配合LightRefBase引用計數使用的智能指針類便是sp了,它也是定義在frameworks/base/include/utils/RefBase.h文件中:
- template <typename T>
- class sp
- {
- public:
- typedef typename RefBase::weakref_type weakref_type;
- inline sp() : m_ptr(0) { }
- sp(T* other);
- sp(const sp<T>& other);
- template<typename U> sp(U* other);
- template<typename U> sp(const sp<U>& other);
- ~sp();
- // Assignment
- sp& operator = (T* other);
- sp& operator = (const sp<T>& other);
- template<typename U> sp& operator = (const sp<U>& other);
- template<typename U> sp& operator = (U* other);
- //! Special optimization for use by ProcessState (and nobody else).
- void force_set(T* other);
- // Reset
- void clear();
- // Accessors
- inline T& operator* () const { return *m_ptr; }
- inline T* operator-> () const { return m_ptr; }
- inline T* get() const { return m_ptr; }
- // Operators
- COMPARE(==)
- COMPARE(!=)
- COMPARE(>)
- COMPARE(<)
- COMPARE(<=)
- COMPARE(>=)
- private:
- template<typename Y> friend class sp;
- template<typename Y> friend class wp;
- // Optimization for wp::promote().
- sp(T* p, weakref_type* refs);
- T* m_ptr;
- };
- template<typename T>
- sp<T>::sp(T* other)
- : m_ptr(other)
- {
- if (other) other->incStrong(this);
- }
- template<typename T>
- sp<T>::sp(const sp<T>& other)
- : m_ptr(other.m_ptr)
- {
- if (m_ptr) m_ptr->incStrong(this);
- }
最後,看一下析構函數:
- template<typename T>
- sp<T>::~sp()
- {
- if (m_ptr) m_ptr->decStrong(this);
- }
輕量級智能指針的實現原理大概就是這樣了,比較簡單,下面我們再用一個例子來說明它的用法。
2. 輕量級指針的用法
參考在Ubuntu上爲Android系統內置C可執行程序測試Linux內核驅動程序一文,我們在external目錄下建立一個C++工程目錄lightpointer,它裏面有兩個文件,一個lightpointer.cpp文件,另外一個是Android.mk文件。
源文件lightpointer.cpp的內容如下:
- #include <stdio.h>
- #include <utils/RefBase.h>
- using namespace android;
- class LightClass : public LightRefBase<LightClass>
- {
- public:
- LightClass()
- {
- printf("Construct LightClass Object.");
- }
- virtual ~LightClass()
- {
- printf("Destory LightClass Object.");
- }
- };
- int main(int argc, char** argv)
- {
- LightClass* pLightClass = new LightClass();
- sp<LightClass> lpOut = pLightClass;
- printf("Light Ref Count: %d.\n", pLightClass->getStrongCount());
- {
- sp<LightClass> lpInner = lpOut;
- printf("Light Ref Count: %d.\n", pLightClass->getStrongCount());
- }
- printf("Light Ref Count: %d.\n", pLightClass->getStrongCount());
- return 0;
- }
編譯腳本文件Android.mk的內容如下:
- LOCAL_PATH := $(call my-dir)
- include $(CLEAR_VARS)
- LOCAL_MODULE_TAGS := optional
- LOCAL_MODULE := lightpointer
- LOCAL_SRC_FILES := lightpointer.cpp
- LOCAL_SHARED_LIBRARIES := \
- libcutils \
- libutils
- include $(BUILD_EXECUTABLE)
- USER-NAME@MACHINE-NAME:~/Android$ mmm ./external/lightpointer
- USER-NAME@MACHINE-NAME:~/Android$ make snod
- USER-NAME@MACHINE-NAME:~/Android$ adb shell
- root@android:/ # cd system/bin/
- root@android:/system/bin # ./lightpointer
- Construct LightClass Object.
- Light Ref Count: 1.
- Light Ref Count: 2.
- Light Ref Count: 1.
- Destory LightClass Object.
這裏可以看出,程序一切都是按照我們的設計來運行,這也驗證了我們上面分析的輕量級智能指針的實現原理。
3. 強指針
強指針所使用的引用計數類爲RefBase,它LightRefBase類要複雜多了,所以才稱後者爲輕量級的引用計數基類吧。我們先來看看RefBase類的實現,它定義在frameworks/base/include/utils/RefBase.h文件中:
- class RefBase
- {
- public:
- void incStrong(const void* id) const;
- void decStrong(const void* id) const;
- void forceIncStrong(const void* id) const;
- //! DEBUGGING ONLY: Get current strong ref count.
- int32_t getStrongCount() const;
- class weakref_type
- {
- public:
- RefBase* refBase() const;
- void incWeak(const void* id);
- void decWeak(const void* id);
- bool attemptIncStrong(const void* id);
- //! This is only safe if you have set OBJECT_LIFETIME_FOREVER.
- 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);
- }
- protected:
- RefBase();
- virtual ~RefBase();
- //! Flags for extendObjectLifetime()
- enum {
- OBJECT_LIFETIME_WEAK = 0x0001,
- OBJECT_LIFETIME_FOREVER = 0x0003
- };
- 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 weakref_type;
- class weakref_impl;
- RefBase(const RefBase& o);
- RefBase& operator=(const RefBase& o);
- weakref_impl* const mRefs;
- };
RefBase類的成員變量mRefs的類型爲weakref_impl指針,它實現在frameworks/base/libs/utils/RefBase.cpp文件中:
- class RefBase::weakref_impl : public RefBase::weakref_type
- {
- public:
- volatile int32_t mStrong;
- volatile int32_t mWeak;
- RefBase* const mBase;
- volatile int32_t mFlags;
- #if !DEBUG_REFS
- weakref_impl(RefBase* base)
- : mStrong(INITIAL_STRONG_VALUE)
- , mWeak(0)
- , mBase(base)
- , mFlags(0)
- {
- }
- void addStrongRef(const void* /*id*/) { }
- void removeStrongRef(const void* /*id*/) { }
- void addWeakRef(const void* /*id*/) { }
- void removeWeakRef(const void* /*id*/) { }
- void printRefs() const { }
- void trackMe(bool, bool) { }
- #else
- weakref_impl(RefBase* base)
- : mStrong(INITIAL_STRONG_VALUE)
- , mWeak(0)
- , mBase(base)
- , mFlags(0)
- , mStrongRefs(NULL)
- , mWeakRefs(NULL)
- , mTrackEnabled(!!DEBUG_REFS_ENABLED_BY_DEFAULT)
- , mRetain(false)
- {
- //LOGI("NEW weakref_impl %p for RefBase %p", this, base);
- }
- ~weakref_impl()
- {
- LOG_ALWAYS_FATAL_IF(!mRetain && mStrongRefs != NULL, "Strong references remain!");
- LOG_ALWAYS_FATAL_IF(!mRetain && mWeakRefs != NULL, "Weak references remain!");
- }
- void addStrongRef(const void* id)
- {
- addRef(&mStrongRefs, id, mStrong);
- }
- void removeStrongRef(const void* id)
- {
- if (!mRetain)
- removeRef(&mStrongRefs, id);
- else
- addRef(&mStrongRefs, id, -mStrong);
- }
- void addWeakRef(const void* id)
- {
- addRef(&mWeakRefs, id, mWeak);
- }
- void removeWeakRef(const void* id)
- {
- if (!mRetain)
- removeRef(&mWeakRefs, id);
- else
- addRef(&mWeakRefs, id, -mWeak);
- }
- void trackMe(bool track, bool retain)
- {
- mTrackEnabled = track;
- mRetain = retain;
- }
- ......
- private:
- struct ref_entry
- {
- ref_entry* next;
- const void* id;
- #if DEBUG_REFS_CALLSTACK_ENABLED
- CallStack stack;
- #endif
- int32_t ref;
- };
- void addRef(ref_entry** refs, const void* id, int32_t mRef)
- {
- if (mTrackEnabled) {
- AutoMutex _l(mMutex);
- ref_entry* ref = new ref_entry;
- // Reference count at the time of the snapshot, but before the
- // update. Positive value means we increment, negative--we
- // decrement the reference count.
- ref->ref = mRef;
- ref->id = id;
- #if DEBUG_REFS_CALLSTACK_ENABLED
- ref->stack.update(2);
- #endif
- ref->next = *refs;
- *refs = ref;
- }
- }
- void removeRef(ref_entry** refs, const void* id)
- {
- if (mTrackEnabled) {
- AutoMutex _l(mMutex);
- ref_entry* ref = *refs;
- while (ref != NULL) {
- if (ref->id == id) {
- *refs = ref->next;
- delete ref;
- return;
- }
- refs = &ref->next;
- ref = *refs;
- }
- LOG_ALWAYS_FATAL("RefBase: removing id %p on RefBase %p (weakref_type %p) that doesn't exist!",
- id, mBase, this);
- }
- }
- ......
- Mutex mMutex;
- ref_entry* mStrongRefs;
- ref_entry* mWeakRefs;
- bool mTrackEnabled;
- // Collect stack traces on addref and removeref, instead of deleting the stack references
- // on removeref that match the address ones.
- bool mRetain;
- ......
- #endif
- };
- #if !DEBUG_REFS
- ......
- #else
- #else
- ......
- #endif
- struct ref_entry
- {
- ref_entry* next;
- const void* id;
- #if DEBUG_REFS_CALLSTACK_ENABLED
- CallStack stack;
- #endif
- int32_t ref;
- };
總的來說,weakref_impl類只要提供了以下四個成員變量來維護對象的引用計數:
- volatile int32_t mStrong;
- volatile int32_t mWeak;
- RefBase* const mBase;
- volatile int32_t mFlags;
- //! Flags for extendObjectLifetime()
- enum {
- OBJECT_LIFETIME_WEAK = 0x0001,
- OBJECT_LIFETIME_FOREVER = 0x0003
- };
說了這多,RefBase類給人的感覺還是挺複雜的,不要緊,我們一步步來,先通過下面這個圖來梳理一下這些類之間的關係:
從這個類圖可以看出,每一個RefBase對象包含了一個weakref_impl對象,而weakref_impl對象實現了weakref_type接口,同時它可以包含多個ref_entry對象,前面說過,ref_entry是調試用的一個結構體,實際使用中可以不關注。
提供引用計數器的類RefBase我們就暫時介紹到這裏,後面我們再結合智能指針類一起分析,現在先來看看強指針類和弱指針類的定義。強指針類的定義我們在前面介紹輕量級指針的時候已經見到了,就是sp類了,這裏就不再把它的代碼列出來了。我們來看看它的構造函數的實現:
- template<typename T>
- sp<T>::sp(T* other)
- : m_ptr(other)
- {
- if (other) other->incStrong(this);
- }
這裏傳進來的參數other一定是繼承於RefBase類的,因此,在函數的內部,它調用的是RefBase類的incStrong函數,它定義在frameworks/base/libs/utils/RefBase.cpp文件中:
- void RefBase::incStrong(const void* id) const
- {
- weakref_impl* const refs = mRefs;
- refs->addWeakRef(id);
- refs->incWeak(id);
- refs->addStrongRef(id);
- const int32_t c = android_atomic_inc(&refs->mStrong);
- LOG_ASSERT(c > 0, "incStrong() called on %p after last strong ref", refs);
- #if PRINT_REFS
- LOGD("incStrong of %p from %p: cnt=%d\n", this, id, c);
- #endif
- if (c != INITIAL_STRONG_VALUE) {
- return;
- }
- android_atomic_add(-INITIAL_STRONG_VALUE, &refs->mStrong);
- const_cast<RefBase*>(this)->onFirstRef();
- }
- RefBase::RefBase()
- : mRefs(new weakref_impl(this))
- {
- // LOGV("Creating refs %p with RefBase %p\n", mRefs, this);
- }
一是增加弱引用計數:
- refs->addWeakRef(id);
- refs->incWeak(id);
- refs->addStrongRef(id);
- const int32_t c = android_atomic_inc(&refs->mStrong);
- if (c != INITIAL_STRONG_VALUE) {
- return;
- }
- android_atomic_add(-INITIAL_STRONG_VALUE, &refs->mStrong);
- const_cast<RefBase*>(this)->onFirstRef();
- #define INITIAL_STRONG_VALUE (1<<28)
回過頭來看弱引用計數是如何增加的,首先是調用weakref_impl類的addWeakRef函數,我們知道,在Release版本中,這個函數也不做,而在Debug版本中,這個函數增加了一個ref_entry對象到了weakref_impl對象的mWeakRefs列表中,表示此weakref_impl對象的弱引用計數被增加了一次。接着又調用了weakref_impl類的incWeak函數,真正增加弱引用計數值就是在這個函數實現的了,weakref_impl類的incWeak函數繼承於其父類weakref_type的incWeak函數:
- void RefBase::weakref_type::incWeak(const void* id)
- {
- weakref_impl* const impl = static_cast<weakref_impl*>(this);
- impl->addWeakRef(id);
- const int32_t c = android_atomic_inc(&impl->mWeak);
- LOG_ASSERT(c >= 0, "incWeak called on %p after last weak ref", this);
- }
- const int32_t c = android_atomic_inc(&impl->mWeak);
http://groups.google.com/group/android-platform/browse_thread/thread/cc641db8487dd83
Ah I see. Well the debug code may be broken, though I wouldn't leap to that
conclusion without actually testing it; I know it has been used in the
past. Anyway, these things get compiled out in non-debug builds, so there
is no reason to change them unless you are actually trying to use this debug
code and it isn't working and need to do this to fix it.
既然他也不知道怎麼回事,我們也不必深究了,知道有這麼回事就行。
這裏總結一下強指針類sp在其構造函數裏面所做的事情就是分別爲目標對象的強引用計數和弱引和計數增加了1。
再來看看強指針類的析構函數的實現:
- template<typename T>
- sp<T>::~sp()
- {
- if (m_ptr) m_ptr->decStrong(this);
- }
- void RefBase::decStrong(const void* id) const
- {
- weakref_impl* const refs = mRefs;
- refs->removeStrongRef(id);
- const int32_t c = android_atomic_dec(&refs->mStrong);
- #if PRINT_REFS
- LOGD("decStrong of %p from %p: cnt=%d\n", this, id, c);
- #endif
- LOG_ASSERT(c >= 1, "decStrong() called on %p too many times", refs);
- if (c == 1) {
- const_cast<RefBase*>(this)->onLastStrongRef(id);
- if ((refs->mFlags&OBJECT_LIFETIME_WEAK) != OBJECT_LIFETIME_WEAK) {
- delete this;
- }
- }
- refs->removeWeakRef(id);
- refs->decWeak(id);
- }
- const int32_t c = android_atomic_dec(&refs->mStrong);
- if (c == 1) {
- const_cast<RefBase*>(this)->onLastStrongRef(id);
- if ((refs->mFlags&OBJECT_LIFETIME_WEAK) != OBJECT_LIFETIME_WEAK) {
- delete this;
- }
- }
接下來的ref->removeWeakRef函數調用語句是對應前面在RefBase::incStrong函數裏的refs->addWeakRef函數調用語句的,在Release版本中,這也是一個空實現函數,真正實現強引用計數減1的操作下面的refs->decWeak函數,weakref_impl類沒有實現自己的decWeak函數,它繼承了weakref_type類的decWeak函數:
- void RefBase::weakref_type::decWeak(const void* id)
- {
- weakref_impl* const impl = static_cast<weakref_impl*>(this);
- impl->removeWeakRef(id);
- const int32_t c = android_atomic_dec(&impl->mWeak);
- LOG_ASSERT(c >= 1, "decWeak called on %p too many times", this);
- if (c != 1) return;
- if ((impl->mFlags&OBJECT_LIFETIME_WEAK) != OBJECT_LIFETIME_WEAK) {
- if (impl->mStrong == INITIAL_STRONG_VALUE)
- delete impl->mBase;
- else {
- // LOGV("Freeing refs %p of old RefBase %p\n", this, impl->mBase);
- delete impl;
- }
- } else {
- impl->mBase->onLastWeakRef(id);
- if ((impl->mFlags&OBJECT_LIFETIME_FOREVER) != OBJECT_LIFETIME_FOREVER) {
- delete impl->mBase;
- }
- }
- }
- const int32_t c = android_atomic_dec(&impl->mWeak);
- if ((impl->mFlags&OBJECT_LIFETIME_WEAK) != OBJECT_LIFETIME_WEAK) {
- if (impl->mStrong == INITIAL_STRONG_VALUE)
- delete impl->mBase;
- else {
- // LOGV("Freeing refs %p of old RefBase %p\n", this, impl->mBase);
- delete impl;
- }
- } else {
- impl->mBase->onLastWeakRef(id);
- if ((impl->mFlags&OBJECT_LIFETIME_FOREVER) != OBJECT_LIFETIME_FOREVER) {
- delete impl->mBase;
- }
- }
- if (impl->mStrong == INITIAL_STRONG_VALUE)
- delete impl->mBase;
- else {
- // LOGV("Freeing refs %p of old RefBase %p\n", this, impl->mBase);
- delete impl;
- }
如果是前一種場景,這裏的impl->mStrong就必然等於0,而不會等於INITIAL_STRONG_VALUE值,因此,這裏就不需要delete目標對象了(impl->mBase),因爲前面的RefBase::decStrong函數會負責delete這個對象。這裏唯一需要做的就是把weakref_impl對象delete掉,但是,爲什麼要在這裏delete這個weakref_impl對象呢?這裏的weakref_impl對象是在RefBase的構造函數裏面new出來的,理論上說應該在在RefBase的析構函數裏delete掉這個weakref_impl對象的。在RefBase的析構函數裏面,的確是會做這件事情:
- RefBase::~RefBase()
- {
- // LOGV("Destroying RefBase %p (refs %p)\n", this, mRefs);
- if (mRefs->mWeak == 0) {
- // LOGV("Freeing refs %p of old RefBase %p\n", mRefs, this);
- delete mRefs;
- }
- }
但是不要忘記,在這個場景下,目標對象是前面的RefBase::decStrong函數delete掉的,這時候目標對象就會被析構,但是它的弱引用計數值尚未執行減1操作,因此,這裏的mRefs->mWeak == 0條件就不成立,於是就不會delete這個weakref_impl對象,因此,就延遲到執行這裏decWeak函數時再執行。
如果是後一種情景,這裏的impl->mStrong值就等於INITIAL_STRONG_VALUE了,這時候由於沒有地方會負責delete目標對象,因此,就需要把目標對象(imp->mBase)delete掉了,否則就會造成內存泄漏。在delete這個目標對象的時候,就會執行RefBase類的析構函數,這時候目標對象的弱引用計數等於0,於是,就會把weakref_impl對象也一起delete掉了。
回到外層的if語句中,如果目標對象的生命週期是受弱引用計數控制的,就執行下面語句:
- impl->mBase->onLastWeakRef(id);
- if ((impl->mFlags&OBJECT_LIFETIME_FOREVER) != OBJECT_LIFETIME_FOREVER) {
- delete impl->mBase;
- }
分析到這裏,有必要小結一下:
A. 如果對象的標誌位被設置爲0,那麼只要發現對象的強引用計數值爲0,那就會自動delete掉這個對象;
B. 如果對象的標誌位被設置爲OBJECT_LIFETIME_WEAK,那麼只有當對象的強引用計數和弱引用計數都爲0的時候,纔會自動delete掉這個對象;
C. 如果對象的標誌位被設置爲OBJECT_LIFETIME_FOREVER,那麼對象就永遠不會自動被delete掉,誰new出來的對象誰來delete掉。
到了這裏,強指針就分析完成了,最後來分析弱指針。
4. 弱指針
弱指針所使用的引用計數類與強指針一樣,都是RefBase類,因此,這裏就不再重複介紹了,我們直接來弱指針的實現,它定義在frameworks/base/include/utils/RefBase.h文件中:
- template <typename T>
- class wp
- {
- public:
- typedef typename RefBase::weakref_type weakref_type;
- inline wp() : m_ptr(0) { }
- wp(T* other);
- wp(const wp<T>& other);
- wp(const sp<T>& other);
- template<typename U> wp(U* other);
- template<typename U> wp(const sp<U>& other);
- template<typename U> wp(const wp<U>& other);
- ~wp();
- // Assignment
- wp& operator = (T* other);
- wp& operator = (const wp<T>& other);
- wp& operator = (const sp<T>& other);
- template<typename U> wp& operator = (U* other);
- template<typename U> wp& operator = (const wp<U>& other);
- template<typename U> wp& operator = (const sp<U>& other);
- void set_object_and_refs(T* other, weakref_type* refs);
- // promotion to sp
- sp<T> promote() const;
- // Reset
- void clear();
- // Accessors
- inline weakref_type* get_refs() const { return m_refs; }
- inline T* unsafe_get() const { return m_ptr; }
- // Operators
- COMPARE_WEAK(==)
- COMPARE_WEAK(!=)
- COMPARE_WEAK(>)
- COMPARE_WEAK(<)
- COMPARE_WEAK(<=)
- COMPARE_WEAK(>=)
- inline bool operator == (const wp<T>& o) const {
- return (m_ptr == o.m_ptr) && (m_refs == o.m_refs);
- }
- template<typename U>
- inline bool operator == (const wp<U>& o) const {
- return m_ptr == o.m_ptr;
- }
- inline bool operator > (const wp<T>& o) const {
- return (m_ptr == o.m_ptr) ? (m_refs > o.m_refs) : (m_ptr > o.m_ptr);
- }
- template<typename U>
- inline bool operator > (const wp<U>& o) const {
- return (m_ptr == o.m_ptr) ? (m_refs > o.m_refs) : (m_ptr > o.m_ptr);
- }
- inline bool operator < (const wp<T>& o) const {
- return (m_ptr == o.m_ptr) ? (m_refs < o.m_refs) : (m_ptr < o.m_ptr);
- }
- template<typename U>
- inline bool operator < (const wp<U>& o) const {
- return (m_ptr == o.m_ptr) ? (m_refs < o.m_refs) : (m_ptr < o.m_ptr);
- }
- inline bool operator != (const wp<T>& o) const { return m_refs != o.m_refs; }
- template<typename U> inline bool operator != (const wp<U>& o) const { return !operator == (o); }
- inline bool operator <= (const wp<T>& o) const { return !operator > (o); }
- template<typename U> inline bool operator <= (const wp<U>& o) const { return !operator > (o); }
- inline bool operator >= (const wp<T>& o) const { return !operator < (o); }
- template<typename U> inline bool operator >= (const wp<U>& o) const { return !operator < (o); }
- private:
- template<typename Y> friend class sp;
- template<typename Y> friend class wp;
- T* m_ptr;
- weakref_type* m_refs;
- };
先來看構造函數:
- template<typename T>
- wp<T>::wp(T* other)
- : m_ptr(other)
- {
- if (other) m_refs = other->createWeak(this);
- }
- RefBase::weakref_type* RefBase::createWeak(const void* id) const
- {
- mRefs->incWeak(id);
- return mRefs;
- }
再來看析構函數:
- template<typename T>
- wp<T>::~wp()
- {
- if (m_ptr) m_refs->decWeak(this);
- }
分析到這裏,弱指針還沒介紹完,它最重要的特性我們還沒有分析到。前面我們說過,弱指針的最大特點是它不能直接操作目標對象,這是怎麼樣做到的呢?祕密就在於弱指針類沒有重載*和->操作符號,而強指針重載了這兩個操作符號。但是,如果我們要操作目標對象,應該怎麼辦呢,這就要把弱指針升級爲強指針了:
- template<typename T>
- sp<T> wp<T>::promote() const
- {
- return sp<T>(m_ptr, m_refs);
- }
我們再來看看這個強指針的構造過程:
- template<typename T>
- sp<T>::sp(T* p, weakref_type* refs)
- : m_ptr((p && refs->attemptIncStrong(this)) ? p : 0)
- {
- }
- bool RefBase::weakref_type::attemptIncStrong(const void* id)
- {
- incWeak(id);
- weakref_impl* const impl = static_cast<weakref_impl*>(this);
- int32_t curCount = impl->mStrong;
- LOG_ASSERT(curCount >= 0, "attemptIncStrong called on %p after underflow",
- this);
- while (curCount > 0 && curCount != INITIAL_STRONG_VALUE) {
- if (android_atomic_cmpxchg(curCount, curCount+1, &impl->mStrong) == 0) {
- break;
- }
- curCount = impl->mStrong;
- }
- if (curCount <= 0 || curCount == INITIAL_STRONG_VALUE) {
- bool allow;
- if (curCount == INITIAL_STRONG_VALUE) {
- // Attempting to acquire first strong reference... this is allowed
- // if the object does NOT have a longer lifetime (meaning the
- // implementation doesn't need to see this), or if the implementation
- // allows it to happen.
- allow = (impl->mFlags&OBJECT_LIFETIME_WEAK) != OBJECT_LIFETIME_WEAK
- || impl->mBase->onIncStrongAttempted(FIRST_INC_STRONG, id);
- } else {
- // Attempting to revive the object... this is allowed
- // if the object DOES have a longer lifetime (so we can safely
- // call the object with only a weak ref) and the implementation
- // allows it to happen.
- allow = (impl->mFlags&OBJECT_LIFETIME_WEAK) == OBJECT_LIFETIME_WEAK
- && impl->mBase->onIncStrongAttempted(FIRST_INC_STRONG, id);
- }
- if (!allow) {
- decWeak(id);
- return false;
- }
- curCount = android_atomic_inc(&impl->mStrong);
- // If the strong reference count has already been incremented by
- // someone else, the implementor of onIncStrongAttempted() is holding
- // an unneeded reference. So call onLastStrongRef() here to remove it.
- // (No, this is not pretty.) Note that we MUST NOT do this if we
- // are in fact acquiring the first reference.
- if (curCount > 0 && curCount < INITIAL_STRONG_VALUE) {
- impl->mBase->onLastStrongRef(id);
- }
- }
- impl->addWeakRef(id);
- impl->addStrongRef(id);
- #if PRINT_REFS
- LOGD("attemptIncStrong of %p from %p: cnt=%d\n", this, id, curCount);
- #endif
- if (curCount == INITIAL_STRONG_VALUE) {
- android_atomic_add(-INITIAL_STRONG_VALUE, &impl->mStrong);
- impl->mBase->onFirstRef();
- }
- return true;
- }
這個函數的作用是試圖增加目標對象的強引用計數,但是有可能會失敗,失敗的原因可能是因爲目標對象已經被delete掉了,或者是其它的原因,下面會分析到。前面我們在討論強指針的時候說到,增加目標對象的強引用計數的同時,也會增加目標對象的弱引用計數,因此,函數在開始的地方首先就是調用incWeak函數來先增加目標對象的引用計數,如果後面試圖增加目標對象的強引用計數失敗時,會調用decWeak函數來回滾前面的incWeak操作。
這裏試圖增加目標對象的強引用計數時,分兩種情況討論,一種情況是此時目標對象正在被其它強指針引用,即它的強引用計數大於0,並且不等於INITIAL_STRONG_VALUE,另一種情況是此時目標對象沒有被任何強指針引用,即它的強引用計數小於等於0,或者等於INITIAL_STRONG_VALUE。
第一種情況比較簡單,因爲這時候說明目標對象一定存在,因此,是可以將這個弱指針提升爲強指針的,在這種情況下,只要簡單地增加目標對象的強引用計數值就行了:
- while (curCount > 0 && curCount != INITIAL_STRONG_VALUE) {
- if (android_atomic_cmpxchg(curCount, curCount+1, &impl->mStrong) == 0) {
- break;
- }
- curCount = impl->mStrong;
- }
- int android_atomic_release_cas(int32_t oldvalue, int32_t newvalue,
- volatile int32_t* addr);
- #define android_atomic_cmpxchg android_atomic_release_cas
第二種情況比較複雜一點,因爲這時候目標對象可能還存在,也可能不存了,這要根據實際情況來判斷。如果此時目標對象的強引用計數值等於INITIAL_STRONG_VALUE,說明此目標對象還從未被強指針引用過,這時候弱指針能夠被提升爲強指針的條件就爲:
- allow = (impl->mFlags&OBJECT_LIFETIME_WEAK) != OBJECT_LIFETIME_WEAK
- || impl->mBase->onIncStrongAttempted(FIRST_INC_STRONG, id);
即如果目標對象的生命週期只受到強引用計數控制或者在目標對象的具體實現中總是允許這種情況發生。怎麼理解呢?如果目標對象的生命週期只受強引用計數控制(它的標誌位mFlags爲0),而這時目標對象又還未被強指針引用過,它自然就不會被delete掉,因此,這時候可以判斷出目標對象是存在的;如果目標對象的生命週期受弱引用計數控制(OBJECT_LIFETIME_WEAK),這時候由於目標對象正在被弱指針引用,因此,弱引用計數一定不爲0,目標對象一定存在;如果目標對象的生命週期不受引用計數控制(BJECT_LIFETIME_FOREVER),這時候目標對象也是下在被弱指針引用,因此,目標對象的所有者必須保證這個目標對象還沒有被delete掉,否則就會出問題了。在後面兩種場景下,因爲目標對象的生命週期都是不受強引用計數控制的,而現在又要把弱指針提升爲強指針,就需要進一步調用目標對象的onIncStrongAttempted來看看是否允許這種情況發生,這又該怎麼理解呢?可以這樣理解,目標對象的設計者可能本身就不希望這個對象被強指針引用,只能通過弱指針來引用它,因此,這裏它就可以重載其父類的onIncStrongAttempted函數,然後返回false,這樣就可以阻止弱指針都被提升爲強指針。在RefBase類中,其成員函數onIncStrongAttempted默認是返回true的:
- bool RefBase::onIncStrongAttempted(uint32_t flags, const void* id)
- {
- return (flags&FIRST_INC_STRONG) ? true : false;
- }
如果此時目標對象的強引用計數值小於等於0,那就說明該對象之前一定被強指針引用過,這時候就必須保證目標對象是被弱引用計數控制的(BJECT_LIFETIME_WEAK),否則的話,目標對象就已經被delete了。同樣,這裏也要調用一下目標對象的onIncStrongAttempted成員函數,來詢問一下目標對象在強引用計數值小於等於0的時候,是否允計將弱指針提升爲強指針。下面這個代碼段就是執行上面所說的邏輯:
- allow = (impl->mFlags&OBJECT_LIFETIME_WEAK) == OBJECT_LIFETIME_WEAK
- && impl->mBase->onIncStrongAttempted(FIRST_INC_STRONG, id);
- if (!allow) {
- decWeak(id);
- return false;
- }
- curCount = android_atomic_inc(&impl->mStrong);
函數attemptIncStrong的主體邏輯大概就是這樣了,比較複雜,讀者要細細體會一下。函數的最後,如果此弱指針是允計提升爲強指針的,並且此目標對象是第一次被強指針引用,還需要調整一下目標對象的強引用計數值:
- if (curCount == INITIAL_STRONG_VALUE) {
- android_atomic_add(-INITIAL_STRONG_VALUE, &impl->mStrong);
- impl->mBase->onFirstRef();
- }
分析到這裏,弱指針就介紹完了。強指針和弱指針的關係比較密切,同時它們也比較複雜,下面我們再舉一個例子來說明強指針和弱指針的用法,同時也驗證一下它們的實現原理。
5. 強指針和弱指針的用法
參考在Ubuntu上爲Android系統內置C可執行程序測試Linux內核驅動程序一文,我們在external目錄下建立一個C++工程目錄weightpointer,它裏面有兩個文件,一個weightpointer.cpp文件,另外一個是Android.mk文件。
源文件weightpointer.cpp的內容如下:
- #include <stdio.h>
- #include <utils/RefBase.h>
- #define INITIAL_STRONG_VALUE (1<<28)
- using namespace android;
- class WeightClass : public RefBase
- {
- public:
- void printRefCount()
- {
- int32_t strong = getStrongCount();
- weakref_type* ref = getWeakRefs();
- printf("-----------------------\n");
- printf("Strong Ref Count: %d.\n", (strong == INITIAL_STRONG_VALUE ? 0 : strong));
- printf("Weak Ref Count: %d.\n", ref->getWeakCount());
- printf("-----------------------\n");
- }
- };
- class StrongClass : public WeightClass
- {
- public:
- StrongClass()
- {
- printf("Construct StrongClass Object.\n");
- }
- virtual ~StrongClass()
- {
- printf("Destory StrongClass Object.\n");
- }
- };
- class WeakClass : public WeightClass
- {
- public:
- WeakClass()
- {
- extendObjectLifetime(OBJECT_LIFETIME_WEAK);
- printf("Construct WeakClass Object.\n");
- }
- virtual ~WeakClass()
- {
- printf("Destory WeakClass Object.\n");
- }
- };
- class ForeverClass : public WeightClass
- {
- public:
- ForeverClass()
- {
- extendObjectLifetime(OBJECT_LIFETIME_FOREVER);
- printf("Construct ForeverClass Object.\n");
- }
- virtual ~ForeverClass()
- {
- printf("Destory ForeverClass Object.\n");
- }
- };
- void TestStrongClass(StrongClass* pStrongClass)
- {
- wp<StrongClass> wpOut = pStrongClass;
- pStrongClass->printRefCount();
- {
- sp<StrongClass> spInner = pStrongClass;
- pStrongClass->printRefCount();
- }
- sp<StrongClass> spOut = wpOut.promote();
- printf("spOut: %p.\n", spOut.get());
- }
- void TestWeakClass(WeakClass* pWeakClass)
- {
- wp<WeakClass> wpOut = pWeakClass;
- pWeakClass->printRefCount();
- {
- sp<WeakClass> spInner = pWeakClass;
- pWeakClass->printRefCount();
- }
- pWeakClass->printRefCount();
- sp<WeakClass> spOut = wpOut.promote();
- printf("spOut: %p.\n", spOut.get());
- }
- void TestForeverClass(ForeverClass* pForeverClass)
- {
- wp<ForeverClass> wpOut = pForeverClass;
- pForeverClass->printRefCount();
- {
- sp<ForeverClass> spInner = pForeverClass;
- pForeverClass->printRefCount();
- }
- }
- int main(int argc, char** argv)
- {
- printf("Test Strong Class: \n");
- StrongClass* pStrongClass = new StrongClass();
- TestStrongClass(pStrongClass);
- printf("\nTest Weak Class: \n");
- WeakClass* pWeakClass = new WeakClass();
- TestWeakClass(pWeakClass);
- printf("\nTest Froever Class: \n");
- ForeverClass* pForeverClass = new ForeverClass();
- TestForeverClass(pForeverClass);
- pForeverClass->printRefCount();
- delete pForeverClass;
- return 0;
- }
在main函數裏面,分別實例化了這三個類的對象出來,然後分別傳給TestStrongClass函數、TestWeakClass函數和TestForeverClass函數來說明智能指針的用法,我們主要是通過考察它們的強引用計數和弱引用計數來驗證智能指針的實現原理。
編譯腳本文件Android.mk的內容如下:
- LOCAL_PATH := $(call my-dir)
- include $(CLEAR_VARS)
- LOCAL_MODULE_TAGS := optional
- LOCAL_MODULE := weightpointer
- LOCAL_SRC_FILES := weightpointer.cpp
- LOCAL_SHARED_LIBRARIES := \
- libcutils \
- libutils
- include $(BUILD_EXECUTABLE)
- USER-NAME@MACHINE-NAME:~/Android$ mmm ./external/weightpointer
- USER-NAME@MACHINE-NAME:~/Android$ make snod
- USER-NAME@MACHINE-NAME:~/Android$ adb shell
- root@android:/ # cd system/bin/
- root@android:/system/bin # ./weightpointer
- Test Strong Class:
- Construct StrongClass Object.
- -----------------------
- Strong Ref Count: 0.
- Weak Ref Count: 1.
- -----------------------
- -----------------------
- Strong Ref Count: 1.
- Weak Ref Count: 2.
- -----------------------
- Destory StrongClass Object.
- spOut: 0x0.
在TestStrongClass函數裏面,首先定義一個弱批針wpOut指向從main函數傳進來的StrongClass對象,這時候我們可以看到StrongClass對象的強引用計數和弱引用計數值分別爲0和1;接着在一個大括號裏面定義一個強指針spInner指向這個StrongClass對象,這時候我們可以看到StrongClass對象的強引用計數和弱引用計數值分別爲1和2;當程序跳出了大括號之後,強指針spInner就被析構了,從上面的分析我們知道,強指針spInner析構時,會減少目標對象的強引用計數值,因爲前面得到的強引用計數值爲1,這裏減1後,就變爲0了,又由於這個StrongClass對象的生命週期只受強引用計數控制,因此,這個StrongClass對象就被delete了,這一點可以從後面的輸出(“Destory StrongClass Object.”)以及試圖把弱指針wpOut提升爲強指針時得到的對象指針爲0x0得到驗證。
執行TestWeakClass函數的輸出爲:
- Test Weak Class:
- Construct WeakClass Object.
- -----------------------
- Strong Ref Count: 0.
- Weak Ref Count: 1.
- -----------------------
- -----------------------
- Strong Ref Count: 1.
- Weak Ref Count: 2.
- -----------------------
- -----------------------
- Strong Ref Count: 0.
- Weak Ref Count: 1.
- -----------------------
- spOut: 0xa528.
- Destory WeakClass Object.
TestWeakClass函數和TestStrongClass函數的執行過程基本一樣,所不同的是當程序跳出大括號之後,雖然這個WeakClass對象的強引用計數值已經爲0,但是由於它的生命週期同時受強引用計數和弱引用計數控制,而這時它的弱引用計數值大於0,因此,這個WeakClass對象不會被delete掉,這一點可以從後面試圖把弱批針wpOut提升爲強指針時得到的對象指針不爲0得到驗證。
執行TestForeverClass函數的輸出來:
- Test Froever Class:
- Construct ForeverClass Object.
- -----------------------
- Strong Ref Count: 0.
- Weak Ref Count: 1.
- -----------------------
- -----------------------
- Strong Ref Count: 1.
- Weak Ref Count: 2.
- -----------------------
- -----------------------
- Strong Ref Count: 0.
- Weak Ref Count: 0.
- -----------------------
- Destory ForeverClass Object.
這樣,從TestStrongClass、TestWeakClass和TestForeverClass這三個函數的輸出就可以驗證了我們上面對Android系統的強指針和弱指針的實現原理的分析。
至此,Android系統的智能指針(輕量級指針、強指針和弱指針)的實現原理就分析完成了,它實現得很小巧但是很精緻,希望讀者可以通過實際操作細細體會一下。
http://blog.csdn.net/luoshengyang/article/details/6786239