編輯:關於 Android 程式設計
在 Android native 層寫程式時,sp 與 wp 幾乎無所不在。這裡的 sp 不是 smart pointer,而是 strong pointer;wp 則是 weak pointer。它們的概念近似 Java 的強引用與弱引用,妥善使用可以讓開發者不必再操心記憶體釋放,避免記憶體洩漏。

要實現自動釋放,sp 與 wp 必須搭配 RefBase 使用。Android 中大多數類別的最上層基類都是 RefBase。以下用一個簡單的類別貫穿說明:
class A : public RefBase { }
RefBase 的建構式會先建立一個 weakref_impl 物件,並為強弱引用計數設初值:
RefBase::RefBase() : mRefs(new weakref_impl(this)) { }
weakref_impl(RefBase* base)
: mStrong(INITIAL_STRONG_VALUE)
, mWeak(0)
, mBase(base)
, mFlags(0) { }
這裡不直接用 0 初始化 mStrong,而是給了 INITIAL_STRONG_VALUE = 0x10000000。目的是方便區分:這個 0 究竟是初始狀態,還是 sp 已經全部釋放後的狀態,兩者需要不同的處理邏輯。
{
sp<A> spA(new A);
}
sp 的建構式把實際物件指標交給 m_ptr,接著呼叫 incStrong:
template<typename T>
sp<T>::sp(T* other) : m_ptr(other) {
if (other) other->incStrong(this);
}
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);
refs->mBase->onFirstRef();
}
流程是:先透過 incWeak 把弱引用計數加一(addStrongRef 只在 debug 版生效),再用原子操作 android_atomic_inc 遞增 mStrong 並取得原值。如果是第一次被引用,還會觸發 onFirstRef 回呼。經過建構式之後,mStrong 與 mWeak 都變成 1。
離開作用域時,sp 的解構式會呼叫 decStrong:
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);
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);
}
若 mStrong 原本為 1,代表已經沒有其他 sp 參照,於是先觸發 onLastStrongRef;如果 Flag 設定為物件生命週期由 sp 決定(這也是預設值),就順勢把 A 物件 delete 掉,最後再呼叫 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);
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 {
impl->mBase->onLastWeakRef(id);
if ((impl->mFlags & OBJECT_LIFETIME_MASK) == OBJECT_LIFETIME_WEAK) {
delete impl->mBase;
}
}
}
若 mWeak 遞減後不為 1,說明還有別的 wp 參照,直接返回;等於 1 時才需要善後。此時依 Flag 決定:生命週期由 sp 主導且先前從未建立過 sp,直接刪除 A 物件;否則只刪掉 weakref_impl 本身,A 物件已在 decStrong 中被清掉。若生命週期由 wp 主導,則先呼叫 onLastWeakRef 再刪除物件。
{
wp<A> wpA(new A);
}
wp 的建構式同樣保存了 A 物件的實際指標,但它沒有重載 ->,所以不能用它直接呼叫 A 的方法。它透過 createWeak 取得弱引用:
template<typename T>
wp<T>::wp(const sp<T>& other) : m_ptr(other.m_ptr) {
if (m_ptr) {
m_refs = m_ptr->createWeak(this);
}
}
RefBase::weakref_type* RefBase::createWeak(const void* id) const {
mRefs->incWeak(id);
return mRefs;
}
注意型別差異:wp 中的 m_refs 是 weakref_type*,RefBase 中的 mRefs 是 weakref_impl*,取用時需要轉型。這個過程只會遞增 mWeak,因此 mStrong 停在 INITIAL_STRONG_VALUE,mWeak 為 1。wpA 離開作用域時呼叫 decWeak,走的就是前面說明過的那條善後邏輯。
{
sp<A> spA(new A);
wp<A> wpA(spA);
}
此時 mStrong 為 1、mWeak 為 2。離開作用域時先解構 wp(mWeak 降為 1),再解構 sp,後者等同應用一的流程。
由於 wp 沒有重載 ->,而且 sp 釋放時物件可能已消失,因此想透過 wp 呼叫方法,必須先把它「升級」成 sp,這靠 promote 完成:
template<typename T>
sp<T> wp<T>::promote() const {
sp<T> result;
if (m_ptr && m_refs->attemptIncStrong(&result)) {
result.set_pointer(m_ptr);
}
return result;
}
attemptIncStrong 的判斷可分為兩大類:
成功遞增後,mStrong 可能大於 INITIAL_STRONG_VALUE,需要再減回 INITIAL_STRONG_VALUE 做校正。當 attemptIncStrong 回傳 true,promote 便以 set_pointer 補上實際指標,之後就能安全地透過 sp 呼叫方法。
這整套設計的精髓在於:sp 決定物件何時存活,wp 只負責「有沒有人還記得這個位址」,兩者透過原子操作搭配引用計數完成自動記憶體管理。
微信個人公眾號改名全攻略 一年僅有一次機會
微信近期悄然上線了個人公眾號改名功能。據了解,原帳號名稱下方會標註「個人類帳號一年內可主動修改一次名稱」,也就是說,一年只有一次改名機會。那麼具體該怎麼操作?下面小編就把
Android 應用信息中「存儲」與「緩存」是怎麼算出來的
路徑:設置 → 應用 → 選一個應用 → 應用信息這個界面會列出應用的磁盤占用:應用、數據、緩存、SD 卡資源、SD 卡緩存,總計一行。這些數字是怎麼算出來的?本文從 J
Android 進程信息查看與內存線索分析
在 Android 中,adb shell 的 ps 指令可快速查看目前執行的行程。這對效能分析、記憶體排查與應用除錯都很實用。使用 ps 查看行程透過 adb shel
Android 基礎(十一):Snackbar
介紹 Snackbars provide lightweight feedback about an operation. They show a brief messa