編輯:關於 Android 程式設計
上一篇分析了強指針 sp,本文接著看弱指針 wp。要理解 wp 存在的意義,先要看一個必然會出事的場景。
假設有兩個類 CParent 與 CChild,父類持有一個指向子對象的強指針,子類也持有一個指向父對象的強指針:
class CParent : public LightRefBase<CParent> {
sp<CChild> spc;
};
class CChild : public LightRefBase<CChild> {
sp<CParent> spp;
};
創建 parent 與 child,令 parent.spc 指向 child、child.spp 指向 parent。此時兩個對象的引用計數都是 1。問題來了:系統一次只能析構一個對象,而每個對象都在等對方的計數歸零,於是誰都析構不掉——形成死鎖,內存洩漏。
弱指針定義在 frameworks/rs/cpp/util/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);
~wp();
wp& operator = (T* other);
wp& operator = (const wp<T>& other);
wp& operator = (const sp<T>& other);
void set_object_and_refs(T* other, weakref_type* refs);
// 升級為強指針
sp<T> promote() const;
void clear();
inline weakref_type* get_refs() const { return m_refs; }
inline T* unsafe_get() const { return m_ptr; }
// 比較運算符 ...(省略)
private:
template<typename Y> friend class sp;
template<typename Y> friend class wp;
T* m_ptr;
weakref_type* m_refs;
};
與 sp 對比,wp 有三處關鍵差異:
weakref_type* 類型的成員 m_refs,指向弱引用計數器;promote() 函數,用於把 wp 臨時升級為 sp;RefBase 而不是 LightRefBase。一、當強引用計數為 0 時,無論弱引用計數是否為 0,都可以釋放該對象。這一條正是循環引用能被打破的根本原因:child 對 parent 用 wp 持有,parent 的強引用計數歸零後立刻被回收,不再等待弱計數。
二、不能通過 wp 直接操作對象,必須先調用 promote() 升級為 sp。這是因為對象隨時可能已被銷毀,升級過程會原子地檢查強引用計數是否為 0,失敗則返回空指針——把「懸垂指針」問題轉化成了可判斷的空值。
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);
// 若已有強引用則獲取強引用
bool attemptIncStrong(const void* id);
bool attemptIncWeak(const void* id);
int32_t getWeakCount() const;
void printRefs() const;
void trackMe(bool enable, bool retain);
};
weakref_type* createWeak(const void* id) const;
weakref_type* getWeakRefs() const;
typedef RefBase basetype;
protected:
RefBase();
virtual ~RefBase();
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:
class weakref_impl;
weakref_impl* const mRefs;
};
LightRefBase 用一個整數 mCount 記錄引用計數,而 RefBase 沒有這樣的整數成員——它的計數器是 mRefs,一個 weakref_impl*。構造函數中完成初始化:
RefBase::RefBase()
: mRefs(new weakref_impl(this))
{
}
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
// ... 調試跟蹤相關實現
#endif
};
weakref_impl 定義很長,但 87 行之後都是 debug 用的,78-85 行的函數全是空實現,可以忽略。真正有內容的只有構造函數的四個初始化。其中:
#define INITIAL_STRONG_VALUE (1<<28)
強引用計數初值是個很大的數,這個偏移量的存在,使得「從無強引用到首次強引用」的判斷可以直接用計數值比較完成,不必額外分支。
wp 的構造函數與賦值運算符:
template<typename T>
wp<T>::wp(T* other)
: m_ptr(other)
{
if (other) m_refs = other->createWeak(this);
}
template<typename T>
wp<T>& wp<T>::operator = (T* other)
{
weakref_type* newRefs = other ? other->createWeak(this) : 0;
if (m_ptr) m_refs->decWeak(this);
m_ptr = other;
m_refs = newRefs;
return *this;
}
注意兩者都沒有直接操作 mWeak,而是通過 createWeak:
RefBase::weakref_type* RefBase::createWeak(const void* id) const
{
mRefs->incWeak(id);
return mRefs;
}
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); // 原子加一
ALOG_ASSERT(c >= 0, "incWeak called on %p after last weak ref", this);
}
返回值 mRefs 被賦給 wp.m_refs,於是 wp 與被指向對象各自持有的指針,指向的是同一個計數器實例。
析構時對稱地減一:
template<typename T>
wp<T>::~wp()
{
if (m_ptr) m_refs->decWeak(this);
}
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);
ALOG_ASSERT(c >= 1, "decWeak called on %p too many times", this);
if (c != 1) return;
if ((impl->mFlags & OBJECT_LIFETIME_WEAK) == OBJECT_LIFETIME_STRONG) {
// 常規情形:對象由最後一個強引用負責銷毀
if (impl->mStrong == INITIAL_STRONG_VALUE) {
// 特例:從未有過強引用,此處直接銷毀對象
delete impl->mBase;
} else {
// 對象已析構,僅釋放計數器本身
delete impl;
}
} else {
// 較少見:生命週期為 OBJECT_LIFETIME_{WEAK|FOREVER}
impl->mBase->onLastWeakRef(id);
if ((impl->mFlags & OBJECT_LIFETIME_MASK) == OBJECT_LIFETIME_WEAK) {
delete impl->mBase;
}
}
}
void RefBase::incStrong(const void* id) const
{
weakref_impl* const refs = mRefs;
refs->incWeak(id); // 強引用同時伴隨一個弱引用
refs->addStrongRef(id); // 空函數
const int32_t c = android_atomic_inc(&refs->mStrong);
ALOG_ASSERT(c > 0, "incStrong() called on %p after last strong ref", refs);
if (c != INITIAL_STRONG_VALUE) {
return; // 非首次強引用,直接返回
}
android_atomic_add(-INITIAL_STRONG_VALUE, &refs->mStrong); // 扣掉偏移量,此時為 1
refs->mBase->onFirstRef();
}
void RefBase::decStrong(const void* id) const
{
weakref_impl* const refs = mRefs;
refs->removeStrongRef(id);
const int32_t c = android_atomic_dec(&refs->mStrong);
ALOG_ASSERT(c >= 1, "decStrong() called on %p too many times", refs);
if (c == 1) {
refs->mBase->onLastStrongRef(id);
if ((refs->mFlags & OBJECT_LIFETIME_MASK) == OBJECT_LIFETIME_STRONG) {
delete this; // 最後一個強引用釋放,對象銷毀
}
}
refs->decWeak(id); // 順帶遞減弱引用計數
}
這裡有個值得留意的細節:incStrong 在增加強引用的同時也增加了一個弱引用。這保證了「只要還有人可能通過 wp 訪問對象,計數器就一定有效」,代價是每次強引用操作多一次原子遞增。
把 parent 對 child 的引用改為 wp,循環就被打破了:parent 析構時,其強引用計數歸零立即釋放,不必等 child 手中的弱引用;child 若此時仍要訪問 parent,promote() 會因強計數為 0 而返回空指針,代碼只需做一次空值判斷。
這就是 Android 智能指針設計的核心取捨:強指針決定對象何時死亡,弱指針決定還能不能安全地問一句「你還在嗎」。
用 Socket 打造自己的 Android 群聊 App(Android 篇)
翻譯自 https://www.androidhive.info/2014/10/android-building-group-chat-app-using-socke
AsyncTask 非同步任務使用
AsyncTask 概念AsyncTask 是 Android 提供的輕量級非同步工具,可在背景執行工作,並在合適時機更新 UI。執行流程呼叫 execute 後,會依序
高仿知乎實作筆記(一):自訂控制元件的封裝與使用
先來看實作後的效果: 從「我的關注」往下,每一列其實都是同一個自訂組合控制元件。這篇就把它從零開始拆解一次。 一、依設計稿完成版面配置 這個頁面的自訂元件中,「夜間模式
Android 自定義 View 高級特效:神奇的貝塞爾曲線
效果預覽 效果圖中我們實現了一個隨手指滑動變化的二階貝塞爾曲線,還有一個能穿越所有已知點的複雜貝塞爾曲線。學會使用貝塞爾曲線後,可以做出 QQ 紅點滑動刪除、360 動