Chromium的智能指針由類scoped_refptr實現。由於它要求被引用對象具有計數功能,因此就提供了一個具有計數功能的基類RefCounted。當一個對象可以被類scoped_refptr描述的對象引用時,它就必須要從基類RefCounted繼承下來。
非線程安全版本:
template <typename T>
struct DefaultRefCountedTraits {
static void Destruct(const T* x) {
RefCounted<T, DefaultRefCountedTraits>::DeleteInternal(x);
}
};
template <class T, typename Traits = DefaultRefCountedTraits<T>>
class RefCounted : public subtle::RefCountedBase {
public:
static constexpr subtle::StartRefCountFromZeroTag kRefCountPreference =
subtle::kStartRefCountFromZeroTag;
RefCounted() : subtle::RefCountedBase(T::kRefCountPreference) {}
void AddRef() const {
subtle::RefCountedBase::AddRef();
}
void Release() const {
if (subtle::RefCountedBase::Release()) {
// Prune the code paths which the static analyzer may take to simulate
// object destruction. Use-after-free errors aren't possible given the
// lifetime guarantees of the refcounting system.
ANALYZER_SKIP_THIS_PATH();
Traits::Destruct(static_cast<const T*>(this));
}
}
protected:
~RefCounted() = default;
private:
friend struct DefaultRefCountedTraits<T>;
template <typename U>
static void DeleteInternal(const U* x) {
delete x;
}
DISALLOW_COPY_AND_ASSIGN(RefCounted);
};
RefCounted類定義了兩個成員函數AddRef和Release,分別用來增加和減少目標對象的1個引用計數,並且都是通過調用父類RefCountedBase的成員函數AddRef和Release來實現的。此類中,在RefCounted::Release()對指針進行釋放,通過調用Traits::Destruct(static_cast<const T*>(this))完成,
結構體DefaultRefCountedTraits::Destruct()調用到自己的私有靜態成員函數對指針進行釋放。
前置定義DefaultRefCountedTraits,通過模板參數Traits=DefaultRefCountedTraits,當它引用的目標對象的引用計數等於0的時候,就會調用該參數Traits指定的類的靜態成員函數Destruct來釋放強制轉換出來的自身對象
其基類實現如下:
class BASE_EXPORT RefCountedBase {
public:
bool HasOneRef() const { return ref_count_ == 1; }
protected:
explicit RefCountedBase(StartRefCountFromZeroTag) {
#if DCHECK_IS_ON()
sequence_checker_.DetachFromSequence();
#endif
}
explicit RefCountedBase(StartRefCountFromOneTag) : ref_count_(1) {
#if DCHECK_IS_ON()
needs_adopt_ref_ = true;
sequence_checker_.DetachFromSequence();
#endif
}
~RefCountedBase() {
#if DCHECK_IS_ON()
DCHECK(in_dtor_) << "RefCounted object deleted without calling Release()";
#endif
}
void AddRef() const {
// TODO(maruel): Add back once it doesn't assert 500 times/sec.
// Current thread books the critical section "AddRelease"
// without release it.
// DFAKE_SCOPED_LOCK_THREAD_LOCKED(add_release_);
#if DCHECK_IS_ON()
DCHECK(!in_dtor_);
DCHECK(!needs_adopt_ref_)
<< "This RefCounted object is created with non-zero reference count."
<< " The first reference to such a object has to be made by AdoptRef or"
<< " MakeRefCounted.";
if (ref_count_ >= 1) {
DCHECK(CalledOnValidSequence());
}
#endif
AddRefImpl();
}
// Returns true if the object should self-delete.
bool Release() const {
--ref_count_;
// TODO(maruel): Add back once it doesn't assert 500 times/sec.
// Current thread books the critical section "AddRelease"
// without release it.
// DFAKE_SCOPED_LOCK_THREAD_LOCKED(add_release_);
#if DCHECK_IS_ON()
DCHECK(!in_dtor_);
if (ref_count_ == 0)
in_dtor_ = true;
if (ref_count_ >= 1)
DCHECK(CalledOnValidSequence());
if (ref_count_ == 1)
sequence_checker_.DetachFromSequence();
#endif
return ref_count_ == 0;
}
// Returns true if it is safe to read or write the object, from a thread
// safety standpoint. Should be DCHECK'd from the methods of RefCounted
// classes if there is a danger of objects being shared across threads.
//
// This produces fewer false positives than adding a separate SequenceChecker
// into the subclass, because it automatically detaches from the sequence when
// the reference count is 1 (and never fails if there is only one reference).
//
// This means unlike a separate SequenceChecker, it will permit a singly
// referenced object to be passed between threads (not holding a reference on
// the sending thread), but will trap if the sending thread holds onto a
// reference, or if the object is accessed from multiple threads
// simultaneously.
bool IsOnValidSequence() const {
#if DCHECK_IS_ON()
return ref_count_ <= 1 || CalledOnValidSequence();
#else
return true;
#endif
}
private:
template <typename U>
friend scoped_refptr<U> base::AdoptRef(U*);
void Adopted() const {
#if DCHECK_IS_ON()
DCHECK(needs_adopt_ref_);
needs_adopt_ref_ = false;
#endif
}
#if defined(ARCH_CPU_64_BIT)
void AddRefImpl() const;
#else
void AddRefImpl() const { ++ref_count_; }
#endif
#if DCHECK_IS_ON()
bool CalledOnValidSequence() const;
#endif
mutable uint32_t ref_count_ = 0;
#if DCHECK_IS_ON()
mutable bool needs_adopt_ref_ = false;
mutable bool in_dtor_ = false;
mutable SequenceChecker sequence_checker_;
#endif
DFAKE_MUTEX(add_release_);
DISALLOW_COPY_AND_ASSIGN(RefCountedBase);
};
在ref_count_==0時,Release()返回true進行指針的釋放,需要注意的是,成員函數AddRef()和Release()均爲const函數,因此ref_count_定義成mutable關鍵字,才能對成員數據進行操作。
線程安全版本:
基類如下:
class BASE_EXPORT RefCountedThreadSafeBase {
public:
bool HasOneRef() const;
protected:
explicit constexpr RefCountedThreadSafeBase(StartRefCountFromZeroTag) {}
explicit constexpr RefCountedThreadSafeBase(StartRefCountFromOneTag)
: ref_count_(1) {
#if DCHECK_IS_ON()
needs_adopt_ref_ = true;
#endif
}
#if DCHECK_IS_ON()
~RefCountedThreadSafeBase();
#else
~RefCountedThreadSafeBase() = default;
#endif
// Release and AddRef are suitable for inlining on X86 because they generate
// very small code sequences. On other platforms (ARM), it causes a size
// regression and is probably not worth it.
#if defined(ARCH_CPU_X86_FAMILY)
// Returns true if the object should self-delete.
bool Release() const { return ReleaseImpl(); }
void AddRef() const { AddRefImpl(); }
#else
// Returns true if the object should self-delete.
bool Release() const;
void AddRef() const;
#endif
private:
template <typename U>
friend scoped_refptr<U> base::AdoptRef(U*);
void Adopted() const {
#if DCHECK_IS_ON()
DCHECK(needs_adopt_ref_);
needs_adopt_ref_ = false;
#endif
}
ALWAYS_INLINE void AddRefImpl() const {
#if DCHECK_IS_ON()
DCHECK(!in_dtor_);
DCHECK(!needs_adopt_ref_)
<< "This RefCounted object is created with non-zero reference count."
<< " The first reference to such a object has to be made by AdoptRef or"
<< " MakeRefCounted.";
#endif
ref_count_.Increment();
}
ALWAYS_INLINE bool ReleaseImpl() const {
#if DCHECK_IS_ON()
DCHECK(!in_dtor_);
DCHECK(!ref_count_.IsZero());
#endif
if (!ref_count_.Decrement()) {
#if DCHECK_IS_ON()
in_dtor_ = true;
#endif
return true;
}
return false;
}
mutable AtomicRefCount ref_count_{0};
#if DCHECK_IS_ON()
mutable bool needs_adopt_ref_ = false;
mutable bool in_dtor_ = false;
#endif
DISALLOW_COPY_AND_ASSIGN(RefCountedThreadSafeBase);
};
可以看到,ref_count_的定義類型爲mutable AtomicRefCount,AtomicRefCount爲一個原子操作類,定義如下:
class AtomicRefCount {
public:
constexpr AtomicRefCount() : ref_count_(0) {}
explicit constexpr AtomicRefCount(int initial_value)
: ref_count_(initial_value) {}
// Increment a reference count.
void Increment() { Increment(1); }
// Increment a reference count by "increment", which must exceed 0.
void Increment(int increment) {
ref_count_.fetch_add(increment, std::memory_order_relaxed);
}
// Decrement a reference count, and return whether the result is non-zero.
// Insert barriers to ensure that state written before the reference count
// became zero will be visible to a thread that has just made the count zero.
bool Decrement() {
// TODO(jbroman): Technically this doesn't need to be an acquire operation
// unless the result is 1 (i.e., the ref count did indeed reach zero).
// However, there are toolchain issues that make that not work as well at
// present (notably TSAN doesn't like it).
return ref_count_.fetch_sub(1, std::memory_order_acq_rel) != 1;
}
// Return whether the reference count is one. If the reference count is used
// in the conventional way, a refrerence count of 1 implies that the current
// thread owns the reference and no other thread shares it. This call
// performs the test for a reference count of one, and performs the memory
// barrier needed for the owning thread to act on the object, knowing that it
// has exclusive access to the object.
bool IsOne() const { return ref_count_.load(std::memory_order_acquire) == 1; }
// Return whether the reference count is zero. With conventional object
// referencing counting, the object will be destroyed, so the reference count
// should never be zero. Hence this is generally used for a debug check.
bool IsZero() const {
return ref_count_.load(std::memory_order_acquire) == 0;
}
// Returns the current reference count (with no barriers). This is subtle, and
// should be used only for debugging.
int SubtleRefCountForDebug() const {
return ref_count_.load(std::memory_order_relaxed);
}
private:
std::atomic_int ref_count_;
};
此類使用了C++ 11特性的 std::atomic_int原子屬性,以此保證線程安全。
/ Default traits for RefCountedThreadSafe<T>. Deletes the object when its ref
// count reaches 0. Overload to delete it on a different thread etc.
template<typename T>
struct DefaultRefCountedThreadSafeTraits {
static void Destruct(const T* x) {
// Delete through RefCountedThreadSafe to make child classes only need to be
// friend with RefCountedThreadSafe instead of this struct, which is an
// implementation detail.
RefCountedThreadSafe<T,
DefaultRefCountedThreadSafeTraits>::DeleteInternal(x);
}
};
//
// A thread-safe variant of RefCounted<T>
//
// class MyFoo : public base::RefCountedThreadSafe<MyFoo> {
// ...
// };
//
// If you're using the default trait, then you should add compile time
// asserts that no one else is deleting your object. i.e.
// private:
// friend class base::RefCountedThreadSafe<MyFoo>;
// ~MyFoo();
//
// We can use REQUIRE_ADOPTION_FOR_REFCOUNTED_TYPE() with RefCountedThreadSafe
// too. See the comment above the RefCounted definition for details.
template <class T, typename Traits = DefaultRefCountedThreadSafeTraits<T> >
class RefCountedThreadSafe : public subtle::RefCountedThreadSafeBase {
public:
static constexpr subtle::StartRefCountFromZeroTag kRefCountPreference =
subtle::kStartRefCountFromZeroTag;
explicit RefCountedThreadSafe()
: subtle::RefCountedThreadSafeBase(T::kRefCountPreference) {}
void AddRef() const {
subtle::RefCountedThreadSafeBase::AddRef();
}
void Release() const {
if (subtle::RefCountedThreadSafeBase::Release()) {
ANALYZER_SKIP_THIS_PATH();
Traits::Destruct(static_cast<const T*>(this));
}
}
protected:
~RefCountedThreadSafe() = default;
private:
friend struct DefaultRefCountedThreadSafeTraits<T>;
template <typename U>
static void DeleteInternal(const U* x) {
delete x;
}
DISALLOW_COPY_AND_ASSIGN(RefCountedThreadSafe);
};
線程安全和非線程安全最大的一個區別就是使用了原子操作的ref_count_成員變量