Chromium的智能指针由类scoped_refptr实现。由于它要求被引用对象具有计数功能,因此就提供了一个具有计数功能的基类RefCounted。当一个对象可以被类scoped_refptr描述的对象引用时,它就必须要从基类RefCounted继承下来。
非线程安全版本:
template
struct DefaultRefCountedTraits {
static void Destruct(const T* x) {
RefCounted::DeleteInternal(x);
}
};
template >
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(this));
}
}
protected:
~RefCounted() = default;
private:
friend struct DefaultRefCountedTraits;
template
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
结构体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
friend scoped_refptr 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
friend scoped_refptr 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. Deletes the object when its ref
// count reaches 0. Overload to delete it on a different thread etc.
template
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::DeleteInternal(x);
}
};
//
// A thread-safe variant of RefCounted
//
// class MyFoo : public base::RefCountedThreadSafe {
// ...
// };
//
// 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();
//
// We can use REQUIRE_ADOPTION_FOR_REFCOUNTED_TYPE() with RefCountedThreadSafe
// too. See the comment above the RefCounted definition for details.
template >
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(this));
}
}
protected:
~RefCountedThreadSafe() = default;
private:
friend struct DefaultRefCountedThreadSafeTraits;
template
static void DeleteInternal(const U* x) {
delete x;
}
DISALLOW_COPY_AND_ASSIGN(RefCountedThreadSafe);
};
线程安全和非线程安全最大的一个区别就是使用了原子操作的ref_count_成员变量