Androidスマートポインタ詳細


ソース:
http://blog.csdn.net/shift_wwwx/articale/detail/78864099
 
前言:
Androidスマートポインタについては、前のspとwpのsource codeを詳しく分析しましたが、まだいくつかの疑問があります.
もっと多くの情報が見られます. spのブログ 和 wpのブログ
 
この論文はAndroid 7.0に基づいてまとめる.
 
ソースコード:
system/core/include/utils/RefBase.h
system/core/include/libutils/RefBase.cpp
 
最初に、spとwpはテンプレート類であり、テンプレートパラメータはTまたはU、コンストラクタまたはリロード演算子の関数に見られるのはT*、U*、あるいはsp&wp&であり、RefBaseとの関係は全く見られなかったということに気づきました.しかし、Androidのspとwpを使っているところを見たら、入ってきたテンプレートのパラメータはすべてRefBaseから継承されています.いわゆるポインタの種類はこのクラスに基づいています.
たとえば:
class MediaPlayer : public BnMediaPlayerClient,
                    public virtual IMediaDeathNotifier
{
public:
    MediaPlayer();
    ~MediaPlayer();
            void            died();
            void            disconnect();
父類はBnMediaPlayer CientとIMediaDeath Notifierで、
class IMediaDeathNotifier: virtual public RefBase
{
public:
    IMediaDeathNotifier() { addObitRecipient(this); }
    virtual ~IMediaDeathNotifier() { removeObitRecipient(this); }
適当に探してください.RefBaseを継承していると見られます.仮想継承です.
 
なお、RefBaseから多くのクラスが引き継がれる可能性がありますので、二義性の継承を避けるためには、RefBaseの派生クラスは仮想的に継承しなければなりません. 
RefBaseの定義を見に来ました.
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);
        
        // 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 weakref_type;
    class weakref_impl;
    
                            RefBase(const RefBase& o);
            RefBase&        operator=(const RefBase& o);

private:
    friend class ReferenceMover;

    static void renameRefs(size_t n, const ReferenceRenamer& renamer);

    static void renameRefId(weakref_type* ref,
            const void* old_id, const void* new_id);

    static void renameRefId(RefBase* ref,
            const void* old_id, const void* new_id);

        weakref_impl* const mRefs;
};
1、spで見た針m_ptrはincStrongとdecStrongでカウントを制御していますが、最終的に呼び出したのはここです.
 
2、wpの中のm_refsのタイプはweakref_です.タイプの針はここでも見られます.
だから、wpの中の指針にとっては、正確にはRefBaseタイプの指針であり、createWeakしか呼び出しられません.incWeakとdecWeakはweakref_です.typeのオブジェクトのみ呼び出しできます.
これはwpブログに残されている問題の第1、2、RefBaseの鍵はmRefsであり、タイプはweakref_であると説明した.impl*、これがスマートフォン全体のキーです.
 
次にRefBaseの実現を詳しく見て、まずRefBaseの構造関数を見てみます.
RefBase::RefBase()
    : mRefs(new weakref_impl(this))
{
}
デフォルトのコンストラクタはmRefsを初期化するため、つまりRefBaseの派生クラスは構造時にmRefsのポインター変数があります. 
 
コア変数mRefsのタイプweakref_を見てください.impl:
class RefBase::weakref_impl : public RefBase::weakref_type
{
public:
    std::atomic    mStrong; //                
    std::atomic    mWeak; //                 
    RefBase* const          mBase; //       ,             ,    mBase    
    std::atomic    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 renameStrongRefId(const void* /*old_id*/, const void* /*new_id*/) { }
    void addWeakRef(const void* /*id*/) { }
    void removeWeakRef(const void* /*id*/) { }
    void renameWeakRefId(const void* /*old_id*/, const void* /*new_id*/) { }
    void printRefs() const { }
    void trackMe(bool, bool) { }

#else

    weakref_impl(RefBase* base) //    
        : mStrong(INITIAL_STRONG_VALUE) //        1<<28
        , mWeak(0) //         0
        , mBase(base) //RefBase,        ,  ,  weakref_impl  delete   ,  mBase    delete,   decWeak
        , mFlags(0)
        , mStrongRefs(NULL) //      ,        
        , mWeakRefs(NULL) //      ,     
        , mTrackEnabled(!!DEBUG_REFS_ENABLED_BY_DEFAULT)
        , mRetain(false)
    {
    }
    
    ~weakref_impl()
    {
        bool dumpStack = false;
        if (!mRetain && mStrongRefs != NULL) {
            dumpStack = true;
            ALOGE("Strong references remain:");
            ref_entry* refs = mStrongRefs;
            while (refs) {
                char inc = refs->ref >= 0 ? '+' : '-';
                ALOGD("\t%c ID %p (ref %d):", inc, refs->id, refs->ref);
#if DEBUG_REFS_CALLSTACK_ENABLED
                refs->stack.log(LOG_TAG);
#endif
                refs = refs->next;
            }
        }

        if (!mRetain && mWeakRefs != NULL) {
            dumpStack = true;
            ALOGE("Weak references remain!");
            ref_entry* refs = mWeakRefs;
            while (refs) {
                char inc = refs->ref >= 0 ? '+' : '-';
                ALOGD("\t%c ID %p (ref %d):", inc, refs->id, refs->ref);
#if DEBUG_REFS_CALLSTACK_ENABLED
                refs->stack.log(LOG_TAG);
#endif
                refs = refs->next;
            }
        }
        if (dumpStack) {
            ALOGE("above errors at:");
            CallStack stack(LOG_TAG);
        }
    }

    void addStrongRef(const void* id) { //           id   mStrongRefs   
        //ALOGD_IF(mTrackEnabled,
        //        "addStrongRef: RefBase=%p, id=%p", mBase, id);
        addRef(&mStrongRefs, id, mStrong.load(std::memory_order_relaxed));
    }

    void removeStrongRef(const void* id) {
        //ALOGD_IF(mTrackEnabled,
        //        "removeStrongRef: RefBase=%p, id=%p", mBase, id);
        if (!mRetain) {
            removeRef(&mStrongRefs, id);
        } else {
            addRef(&mStrongRefs, id, -mStrong.load(std::memory_order_relaxed));
        }
    }

    void renameStrongRefId(const void* old_id, const void* new_id) {
        //ALOGD_IF(mTrackEnabled,
        //        "renameStrongRefId: RefBase=%p, oid=%p, nid=%p",
        //        mBase, old_id, new_id);
        renameRefsId(mStrongRefs, old_id, new_id);
    }

    void addWeakRef(const void* id) { //         id    mWeakRefs 
        addRef(&mWeakRefs, id, mWeak.load(std::memory_order_relaxed));
    }

    void removeWeakRef(const void* id) {
        if (!mRetain) {
            removeRef(&mWeakRefs, id);
        } else {
            addRef(&mWeakRefs, id, -mWeak.load(std::memory_order_relaxed));
        }
    }

    void renameWeakRefId(const void* old_id, const void* new_id) {
        renameRefsId(mWeakRefs, old_id, new_id);
    }

    void trackMe(bool track, bool retain)
    { 
        mTrackEnabled = track;
        mRetain = retain;
    }

    void printRefs() const //          
    {
        String8 text;

        {
            Mutex::Autolock _l(mMutex);
            char buf[128];
            sprintf(buf, "Strong references on RefBase %p (weakref_type %p):
", mBase, this); text.append(buf); printRefsLocked(&text, mStrongRefs); sprintf(buf, "Weak references on RefBase %p (weakref_type %p):
", mBase, this); text.append(buf); printRefsLocked(&text, mWeakRefs); } { char name[100]; snprintf(name, 100, DEBUG_REFS_CALLSTACK_PATH "/%p.stack", this); int rc = open(name, O_RDWR | O_CREAT | O_APPEND, 644); if (rc >= 0) { write(rc, text.string(), text.length()); close(rc); ALOGD("STACK TRACE for %p saved in %s", this, name); } else ALOGE("FAILED TO PRINT STACK TRACE for %p in %s: %s", this, name, strerror(errno)); } } 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* const head = *refs; ref_entry* ref = head; while (ref != NULL) { if (ref->id == id) { *refs = ref->next; delete ref; return; } refs = &ref->next; ref = *refs; } ALOGE("RefBase: removing id %p on RefBase %p" "(weakref_type %p) that doesn't exist!", id, mBase, this); ref = head; while (ref) { char inc = ref->ref >= 0 ? '+' : '-'; ALOGD("\t%c ID %p (ref %d):", inc, ref->id, ref->ref); ref = ref->next; } CallStack stack(LOG_TAG); } } void renameRefsId(ref_entry* r, const void* old_id, const void* new_id) { if (mTrackEnabled) { AutoMutex _l(mMutex); ref_entry* ref = r; while (ref != NULL) { if (ref->id == old_id) { ref->id = new_id; } ref = ref->next; } } } void printRefsLocked(String8* out, const ref_entry* refs) const { char buf[128]; while (refs) { char inc = refs->ref >= 0 ? '+' : '-'; sprintf(buf, "\t%c ID %p (ref %d):
", inc, refs->id, refs->ref); out->append(buf); #if DEBUG_REFS_CALLSTACK_ENABLED out->append(refs->stack.toString("\t\t")); #else out->append("\t\t(call stacks disabled)"); #endif refs = refs->next; } } mutable 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 };
 
またincWeakを見に来てください.
void RefBase::weakref_type::incWeak(const void* id)
{
    weakref_impl* const impl = static_cast(this);
    impl->addWeakRef(id);//         
    const int32_t c __unused = impl->mWeak.fetch_add(1,
            std::memory_order_relaxed); //   1
    ALOG_ASSERT(c >= 0, "incWeak called on %p after last weak ref", this);
}
addWeakRef():
    void addWeakRef(const void* id) {
        addRef(&mWeakRefs, id, mWeak.load(std::memory_order_relaxed));
    }
弱引用をチェーンに追加します.decWeakを見に来てください.
void RefBase::weakref_type::decWeak(const void* id)
{
    weakref_impl* const impl = static_cast(this);
    impl->removeWeakRef(id); //     
    const int32_t c = impl->mWeak.fetch_sub(1, std::memory_order_release); //   1
    ALOG_ASSERT(c >= 1, "decWeak called on %p too many times", this);
    if (c != 1) return; //            ,    
    atomic_thread_fence(std::memory_order_acquire);

    int32_t flags = impl->mFlags.load(std::memory_order_relaxed);
    if ((flags&OBJECT_LIFETIME_MASK) == OBJECT_LIFETIME_STRONG) {
        // This is the regular lifetime case. The object is destroyed
        // when the last strong reference goes away. Since weakref_impl
        // outlive the object, it is not destroyed in the dtor, and
        // we'll have to do it here.
        if (impl->mStrong.load(std::memory_order_relaxed)
                == INITIAL_STRONG_VALUE) {
            // Special case: we never had a strong reference, so we need to
            // destroy the object now.
            delete impl->mBase; //          ,        
        } else {
            // ALOGV("Freeing refs %p of old RefBase %p
", this, impl->mBase); delete impl; } } else { // This is the OBJECT_LIFETIME_WEAK case. The last weak-reference // is gone, we can destroy the object. impl->mBase->onLastWeakRef(id); delete impl->mBase; // , } }
 
次にincStrong():
void RefBase::incStrong(const void* id) const
{
    weakref_impl* const refs = mRefs;
    refs->incWeak(id); //              
    
    refs->addStrongRef(id); //       
    const int32_t c = refs->mStrong.fetch_add(1, std::memory_order_relaxed);
    ALOG_ASSERT(c > 0, "incStrong() called on %p after last strong ref", refs);
#if PRINT_REFS
    ALOGD("incStrong of %p from %p: cnt=%d
", this, id, c); #endif if (c != INITIAL_STRONG_VALUE) { // return; } int32_t old = refs->mStrong.fetch_sub(INITIAL_STRONG_VALUE, std::memory_order_relaxed); // A decStrong() must still happen after us. ALOG_ASSERT(old > INITIAL_STRONG_VALUE, "0x%x too small", old); refs->mBase->onFirstRef(); // onFirstRef() }
 
decStrong():
void RefBase::decStrong(const void* id) const
{
    weakref_impl* const refs = mRefs;
    refs->removeStrongRef(id);//           id
    const int32_t c = refs->mStrong.fetch_sub(1, std::memory_order_release);//   1
#if PRINT_REFS
    ALOGD("decStrong of %p from %p: cnt=%d
", this, id, c); #endif ALOG_ASSERT(c >= 1, "decStrong() called on %p too many times", refs); if (c == 1) {// , std::atomic_thread_fence(std::memory_order_acquire); refs->mBase->onLastStrongRef(id); int32_t flags = refs->mFlags.load(std::memory_order_relaxed); if ((flags&OBJECT_LIFETIME_MASK) == OBJECT_LIFETIME_STRONG) { delete this; // Since mStrong had been incremented, the destructor did not // delete refs. } } // Note that even with only strong reference operations, the thread // deallocating this may not be the same as the thread deallocating refs. // That's OK: all accesses to this happen before its deletion here, // and all accesses to refs happen before its deletion in the final decWeak. // The destructor can safely access mRefs because either it's deleting // mRefs itself, or it's running entirely before the final mWeak decrement. refs->decWeak(id);// , }
このように wpブログの第2、4は説明済みです.
 
まとめてみます
1、incStrongとincWeakの方法は簡単です.強い引用と弱い引用数を増やすことです.注意すべきなのは、incStrongの方法でincWeak方法を呼び出すことです.2、decWeak方法はちょっと複雑です.やるべきことは二つあります.真実の対象を釈放するかどうか、影の対象を釈放するかどうか.弱いアプリケーションのカウントが0かどうかは、真実のオブジェクトと影のオブジェクトを解放するかどうか2)ライフサイクルが強い場合、ここでも判断したいのですが、強い引用数が0であれば、真実のオブジェクトを解放する必要があります.弱い引用数は0です.影のオブジェクトを解放するかどうかはここから見られます.弱い引用数は影の対象に関係しています.弱い引用数が0なら、影の対象は必ず釈放します.しかし、真実の対象は強い引用数を釈放する必要はありません.強い引用数が0なら、真実の対象は必ず釈放します.しかし影の対象は3、decStrong方法を釈放する必要はありません.強い引用と真実のオブジェクトとの関連付けの4、RefBaseの解析方法:真実のオブジェクトが破壊された場合、影のオブジェクトを解放する作業が必要です.影のオブジェクトを放出するのは2つのシーンがあります.リリースです
 
RefBaseの実行過程によって、wpの構造に合わせて、最終的にwpでメンテナンスされるm_ptrは使用していないところで、全体の過程は弱い引用のチェーンを維持しています.
 
したがって、wpを使用するにはpromote関数を通じてspに変換し、spのリロード演算子*と演算子->を介してポインタのメンバーを呼び出す必要があります.
これはつまりwpブログの第3点を説明しました.
 
androidにはRefBase以外にもライト級の引用Light RefBaseがあります.前に見たのは多くの種類がRefBaseを継承しています.後ろにsp、wpを通じてスマートポインタが実現されました.
カウントだけでスマートポインタを使いたいなら、Light RefBaseを使ってもいいです.
まず、Light RefBaseの定義を見てみます.
template 
class LightRefBase
{
public:
    inline LightRefBase() : mCount(0) { }
    inline void incStrong(__attribute__((unused)) const void* id) const {
        mCount.fetch_add(1, std::memory_order_relaxed);
    }
    inline void decStrong(__attribute__((unused)) const void* id) const {
        if (mCount.fetch_sub(1, std::memory_order_release) == 1) {
            std::atomic_thread_fence(std::memory_order_acquire);
            delete static_cast(this);
        }
    }
    //! DEBUGGING ONLY: Get current strong ref count.
    inline int32_t getStrongCount() const {
        return mCount.load(std::memory_order_relaxed);
    }

    typedef LightRefBase basetype;

protected:
    inline ~LightRefBase() { }

private:
    friend class ReferenceMover;
    inline static void renameRefs(size_t n, const ReferenceRenamer& renamer) { }
    inline static void renameRefId(T* ref,
            const void* old_id, const void* new_id) { }

private:
    mutable std::atomic mCount;
};
全体の定義から見れば、コア変数mCountについては、なぜここにincStrong、decStrongがありますか?
 
例を見てもいいです.
class MyClass : virtual public LightRefBase {
public:
    void test();
};
メールで使う時はspで使うべきです.
sp sp(new MyClass());
sp->test();
 
1、Light RefBaseはRefBaseと同じで、必ずあるポインタのベースでなければなりません.
2、Light RefBaseライト級参照は、複雑なOOPではなく、テンプレート構造を採用しています.仮想継承は必要ありません.
3、ライト級参照ベースは軽くメモリにあり、1つのメンバー変数だけを持って、数えます.その引用カウンタクラスのテンプレートには虚関数が含まれていません.端端類(他のクラスに継承されていないクラス)が直接参照カウンタベースクラスを継承する場合、端端類も虚の解析関数が必要ではなく、部分削除によってメモリリークが発生することはありません.テンプレートコードの中にstatic_uを使用しています.castは下に転換し、テンプレートは安全を確保する.
4、RefBaseは弱い引用を持っています.ポインタを持っています.削除作業を行う時は複雑です.
 
欠陥:
1、弱い引用はサポートされていません.2、ライト級引用類、モジュラス技術を使用しているので、モジュラス技術の欠陥もあります.ライト級引用もあります.明らかな点はライト級の引用類がたくさん必要です.3、コンパイルレベルは参照スタックのオブジェクトをサポートしています.運行時には崩壊します.Scrott Meyersはコンパイラが許可する限り、誰かが必ずそうすると言っています.この問題は利用者が解決する必要があります. friend class refbase
これで、アンディの中では指針の部分だけが一段落し、後期に問題があったら、説明を続けます.大神さんも教えてください. 
 
参考:
http://blog.csdn.net/xielinhua88/article/details/51823442
http://blog.csdn.net/zjq2008wd/article/details/17614417
https://www.cnblogs.com/angeldevil/archive/2013/03/10/2952586.html