Android智能指针(二):RefBase

目录

代码

class Apublic RefBase
{
 //A没有任何自己的功能
}

int main()
{
  A* pA =new A;
    ...
}

这篇主要来讲述类的定义和创建该对象的时候,做了哪些事情。首先我们了解一下父类refbase.

RefBase

refbase的定义在system/core/libutils中,同时,我们看到DEBUG_REFS为0. 那么我们就可以先看非debug版本的refs。首先我们来看一下整体的定义。

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
    {
    。。。 // 省略weakref_type的定义
    };

            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
    };

    // Invoked after creation of initial strong pointer/reference.
    virtual void            onFirstRef();
    // Invoked when either the last strong reference goes away, or we need to undo
    // the effect of an unnecessary onIncStrongAttempted.
    virtual void            onLastStrongRef(const void* id);
    // Only called in OBJECT_LIFETIME_WEAK case.  Returns true if OK to promote to
    // strong reference. May have side effects if it returns true.
    // The first flags argument is always FIRST_INC_STRONG.
    // TODO: Remove initial flag argument.
    virtual bool            onIncStrongAttempted(uint32_t flags, const void* id);
    // Invoked in the OBJECT_LIFETIME_WEAK case when the last reference of either
    // kind goes away.  Unused.
    // TODO: Remove.
    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;
};

好,一开始代码肯定不可能完全记住,那我们就按照代码写的来,最后再补充细节。首先我们看如何创建的。

RefBase::RefBase()
    : mRefs(new weakref_impl(this))
{
}

在创建的时候,会新建一个weakref_impl类型的变量赋值给mRefs,好的,那么我们看一下weakref_impl的定义。

class RefBase::weakref_impl : public RefBase::weakref_type
{
public:
    std::atomic<int32_t>    mStrong;
    std::atomic<int32_t>    mWeak;
    RefBase* const          mBase;
    std::atomic<int32_t>    mFlags;
    //因为我们没开debug模式,所以先关注没debug模式的代码
    explicit 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) { }
};

好的,我们可以看到,这个impl集成自weakref_type,但是他真身还有strong,weak,以及flags的原子操作数。同时我们再看一下weakref_type

    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_impl的定义。也就是定义了一些常用的方法。现在我们捋一下。class A创建的过程。首先,创建了一个type为weakrefs_impl的mrefs。这个refs中有strong,和weak的计数。同时,这个weakrefs_impl又是weakrefs_type,提供了方法来操作这些计数。那么我们就可以总结出来:在创建A的同时,我们创建了一个叫做mRefs的影子weakref_impl的影子对象。里面保存了计数,而且能够进行计数的增加和减少操作。

总结

虽然我们此处用的比较简单,因为我们例子就写的比较简单。但是还是有一些其他的成员是我们需要去记忆的。都在类图中了。总结下来就是,每一个需要只能指针的变量,都必须是refbase的子类。在创建该类的时候,会初始化一个类型为weakref_impl的影子变量mrefs用来记录强弱引用的指针。同时,sp和wp其实都是对mrefs也就是weakref_impl的操作。至于weakref_type是refbase的内部类,定义了影子对象的操作接口,而weakref_impl是对应的实现。实现了对应的影子对象操作接口。 img