scoped_refptr
AdoptRef
1 2 |
template <typename T> scoped_refptr<T> AdoptRef(T* t); |
RefCounted及基类概要
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
class BASE_EXPORT RefCountedBase { public: RefCountedBase(const RefCountedBase&) = delete; RefCountedBase& operator=(const RefCountedBase&) = delete; bool HasOneRef() const { return ref_count_ == 1; } bool HasAtLeastOneRef() const { return ref_count_ >= 1; } protected: // ... void AddRef() const { // ... AddRefImpl(); } bool Release() const { ReleaseImpl(); // ... return ref_count_ == 0; } // ... private: template <typename U> friend scoped_refptr<U> base::AdoptRef(U*); // ... void AddRefImpl() const; void ReleaseImpl() const; private: mutable uint32_t ref_count_ = 0; static_assert(std::is_unsigned<decltype(ref_count_)>::value, "ref_count_ must be an unsigned type."); // ... } template <class T, typename Traits = DefaultRefCountedTraits<T>> class RefCounted : public subtle::RefCountedBase { public: // ... void AddRef() const { subtle::RefCountedBase::AddRef(); } void Release() const { if (subtle::RefCountedBase::Release()) { ANALYZER_SKIP_THIS_PATH(); Traits::Destruct(static_cast<const T*>(this)); } } } |
通过衰减类型类比较是否是一样的类型
1 2 3 4 5 6 7 8 |
template <typename T, typename U, typename V> constexpr bool IsRefCountPreferenceOverridden(const T*, const RefCounted<U, V>*) { return !std::is_same_v<std::decay_t<decltype(GetRefCountPreference<T>())>, std::decay_t<decltype(GetRefCountPreference<U>())>>; } // ... |
判断U是不是T的基类
1 2 3 4 5 6 7 |
template <typename T, typename U, typename V> constexpr void AssertRefCountBaseMatches(const T*, const RefCounted<U, V>*) { static_assert(std::is_base_of_v<U, T>, "T implements RefCounted<U>, but U is not a base of T."); } // ... |
scoped_refptr
- 判断类型U是否可转换为类型T
- 如果可以的话,
std::is_convertible<U*, T*>::value
值为true,反之为false - true的话,
std::enable_if
将使用默认的类型参数作为模板参数来实例化模板 - false的话,
std::enable_if
将禁用模板实例化
- 如果可以的话,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
template <class T> class TRIVIAL_ABI scoped_refptr { public: // ... scoped_refptr(T* p) : ptr_(p) { if (ptr_) AddRef(ptr_); } scoped_refptr(const scoped_refptr& r) : scoped_refptr(r.ptr_) {} // 1 template <typename U, typename = typename std::enable_if< std::is_convertible<U*, T*>::value>::type> scoped_refptr(const scoped_refptr<U>& r) : scoped_refptr(r.ptr_) {} // 移动构造 T* get() const { return ptr_; } T& operator*() const { DCHECK(ptr_); return *ptr_; } T* operator->() const { DCHECK(ptr_); return ptr_; } // ... protected: RAW_PTR_EXCLUSION T* ptr_ = nullptr; } |
本文为原创文章,版权归Aet所有,欢迎分享本文,转载请保留出处!