SkRefCnt.h revision a69f4cf0a7093aa8474b8177627e3976d4f1d9de
1/* 2 * Copyright 2006 The Android Open Source Project 3 * 4 * Use of this source code is governed by a BSD-style license that can be 5 * found in the LICENSE file. 6 */ 7 8#ifndef SkRefCnt_DEFINED 9#define SkRefCnt_DEFINED 10 11#include "../private/SkTLogic.h" 12#include "SkTypes.h" 13#include <atomic> 14#include <functional> 15#include <memory> 16#include <type_traits> 17#include <utility> 18 19/** \class SkRefCntBase 20 21 SkRefCntBase is the base class for objects that may be shared by multiple 22 objects. When an existing owner wants to share a reference, it calls ref(). 23 When an owner wants to release its reference, it calls unref(). When the 24 shared object's reference count goes to zero as the result of an unref() 25 call, its (virtual) destructor is called. It is an error for the 26 destructor to be called explicitly (or via the object going out of scope on 27 the stack or calling delete) if getRefCnt() > 1. 28*/ 29class SK_API SkRefCntBase : SkNoncopyable { 30public: 31 /** Default construct, initializing the reference count to 1. 32 */ 33 SkRefCntBase() : fRefCnt(1) {} 34 35 /** Destruct, asserting that the reference count is 1. 36 */ 37 virtual ~SkRefCntBase() { 38#ifdef SK_DEBUG 39 SkASSERTF(getRefCnt() == 1, "fRefCnt was %d", getRefCnt()); 40 // illegal value, to catch us if we reuse after delete 41 fRefCnt.store(0, std::memory_order_relaxed); 42#endif 43 } 44 45#ifdef SK_DEBUG 46 /** Return the reference count. Use only for debugging. */ 47 int32_t getRefCnt() const { 48 return fRefCnt.load(std::memory_order_relaxed); 49 } 50 51 void validate() const { 52 SkASSERT(getRefCnt() > 0); 53 } 54#endif 55 56 /** May return true if the caller is the only owner. 57 * Ensures that all previous owner's actions are complete. 58 */ 59 bool unique() const { 60 if (1 == fRefCnt.load(std::memory_order_acquire)) { 61 // The acquire barrier is only really needed if we return true. It 62 // prevents code conditioned on the result of unique() from running 63 // until previous owners are all totally done calling unref(). 64 return true; 65 } 66 return false; 67 } 68 69 /** Increment the reference count. Must be balanced by a call to unref(). 70 */ 71 void ref() const { 72 SkASSERT(getRefCnt() > 0); 73 // No barrier required. 74 (void)fRefCnt.fetch_add(+1, std::memory_order_relaxed); 75 } 76 77 /** Decrement the reference count. If the reference count is 1 before the 78 decrement, then delete the object. Note that if this is the case, then 79 the object needs to have been allocated via new, and not on the stack. 80 */ 81 void unref() const { 82 SkASSERT(getRefCnt() > 0); 83 // A release here acts in place of all releases we "should" have been doing in ref(). 84 if (1 == fRefCnt.fetch_add(-1, std::memory_order_acq_rel)) { 85 // Like unique(), the acquire is only needed on success, to make sure 86 // code in internal_dispose() doesn't happen before the decrement. 87 this->internal_dispose(); 88 } 89 } 90 91protected: 92 /** 93 * Allow subclasses to call this if they've overridden internal_dispose 94 * so they can reset fRefCnt before the destructor is called or if they 95 * choose not to call the destructor (e.g. using a free list). 96 */ 97 void internal_dispose_restore_refcnt_to_1() const { 98 SkASSERT(0 == getRefCnt()); 99 fRefCnt.store(1, std::memory_order_relaxed); 100 } 101 102private: 103 /** 104 * Called when the ref count goes to 0. 105 */ 106 virtual void internal_dispose() const { 107 this->internal_dispose_restore_refcnt_to_1(); 108 delete this; 109 } 110 111 // The following friends are those which override internal_dispose() 112 // and conditionally call SkRefCnt::internal_dispose(). 113 friend class SkWeakRefCnt; 114 115 mutable std::atomic<int32_t> fRefCnt; 116 117 typedef SkNoncopyable INHERITED; 118}; 119 120#ifdef SK_REF_CNT_MIXIN_INCLUDE 121// It is the responsibility of the following include to define the type SkRefCnt. 122// This SkRefCnt should normally derive from SkRefCntBase. 123#include SK_REF_CNT_MIXIN_INCLUDE 124#else 125class SK_API SkRefCnt : public SkRefCntBase { 126 // "#include SK_REF_CNT_MIXIN_INCLUDE" doesn't work with this build system. 127 #if defined(GOOGLE3) 128 public: 129 void deref() const { this->unref(); } 130 #endif 131}; 132#endif 133 134/////////////////////////////////////////////////////////////////////////////// 135 136/** Helper macro to safely assign one SkRefCnt[TS]* to another, checking for 137 null in on each side of the assignment, and ensuring that ref() is called 138 before unref(), in case the two pointers point to the same object. 139 */ 140#define SkRefCnt_SafeAssign(dst, src) \ 141 do { \ 142 if (src) src->ref(); \ 143 if (dst) dst->unref(); \ 144 dst = src; \ 145 } while (0) 146 147 148/** Call obj->ref() and return obj. The obj must not be nullptr. 149 */ 150template <typename T> static inline T* SkRef(T* obj) { 151 SkASSERT(obj); 152 obj->ref(); 153 return obj; 154} 155 156/** Check if the argument is non-null, and if so, call obj->ref() and return obj. 157 */ 158template <typename T> static inline T* SkSafeRef(T* obj) { 159 if (obj) { 160 obj->ref(); 161 } 162 return obj; 163} 164 165/** Check if the argument is non-null, and if so, call obj->unref() 166 */ 167template <typename T> static inline void SkSafeUnref(T* obj) { 168 if (obj) { 169 obj->unref(); 170 } 171} 172 173template<typename T> static inline void SkSafeSetNull(T*& obj) { 174 if (obj) { 175 obj->unref(); 176 obj = nullptr; 177 } 178} 179 180/////////////////////////////////////////////////////////////////////////////// 181 182// This is a variant of SkRefCnt that's Not Virtual, so weighs 4 bytes instead of 8 or 16. 183// There's only benefit to using this if the deriving class does not otherwise need a vtable. 184template <typename Derived> 185class SkNVRefCnt : SkNoncopyable { 186public: 187 SkNVRefCnt() : fRefCnt(1) {} 188 ~SkNVRefCnt() { SkASSERTF(1 == getRefCnt(), "NVRefCnt was %d", getRefCnt()); } 189 190 // Implementation is pretty much the same as SkRefCntBase. All required barriers are the same: 191 // - unique() needs acquire when it returns true, and no barrier if it returns false; 192 // - ref() doesn't need any barrier; 193 // - unref() needs a release barrier, and an acquire if it's going to call delete. 194 195 bool unique() const { return 1 == fRefCnt.load(std::memory_order_acquire); } 196 void ref() const { (void)fRefCnt.fetch_add(+1, std::memory_order_relaxed); } 197 void unref() const { 198 if (1 == fRefCnt.fetch_add(-1, std::memory_order_acq_rel)) { 199 // restore the 1 for our destructor's assert 200 SkDEBUGCODE(fRefCnt.store(1, std::memory_order_relaxed)); 201 delete (const Derived*)this; 202 } 203 } 204 void deref() const { this->unref(); } 205 206private: 207 mutable std::atomic<int32_t> fRefCnt; 208 int32_t getRefCnt() const { 209 return fRefCnt.load(std::memory_order_relaxed); 210 } 211}; 212 213/////////////////////////////////////////////////////////////////////////////////////////////////// 214 215/** 216 * Shared pointer class to wrap classes that support a ref()/unref() interface. 217 * 218 * This can be used for classes inheriting from SkRefCnt, but it also works for other 219 * classes that match the interface, but have different internal choices: e.g. the hosted class 220 * may have its ref/unref be thread-safe, but that is not assumed/imposed by sk_sp. 221 */ 222template <typename T> class sk_sp { 223 /** Supports safe bool idiom. Obsolete with explicit operator bool. */ 224 using unspecified_bool_type = T* sk_sp::*; 225public: 226 using element_type = T; 227 228 constexpr sk_sp() : fPtr(nullptr) {} 229 constexpr sk_sp(std::nullptr_t) : fPtr(nullptr) {} 230 231 /** 232 * Shares the underlying object by calling ref(), so that both the argument and the newly 233 * created sk_sp both have a reference to it. 234 */ 235 sk_sp(const sk_sp<T>& that) : fPtr(SkSafeRef(that.get())) {} 236 template <typename U, typename = skstd::enable_if_t<std::is_convertible<U*, T*>::value>> 237 sk_sp(const sk_sp<U>& that) : fPtr(SkSafeRef(that.get())) {} 238 239 /** 240 * Move the underlying object from the argument to the newly created sk_sp. Afterwards only 241 * the new sk_sp will have a reference to the object, and the argument will point to null. 242 * No call to ref() or unref() will be made. 243 */ 244 sk_sp(sk_sp<T>&& that) : fPtr(that.release()) {} 245 template <typename U, typename = skstd::enable_if_t<std::is_convertible<U*, T*>::value>> 246 sk_sp(sk_sp<U>&& that) : fPtr(that.release()) {} 247 248 /** 249 * Adopt the bare pointer into the newly created sk_sp. 250 * No call to ref() or unref() will be made. 251 */ 252 explicit sk_sp(T* obj) : fPtr(obj) {} 253 254 /** 255 * Calls unref() on the underlying object pointer. 256 */ 257 ~sk_sp() { 258 SkSafeUnref(fPtr); 259 SkDEBUGCODE(fPtr = nullptr); 260 } 261 262 sk_sp<T>& operator=(std::nullptr_t) { this->reset(); return *this; } 263 264 /** 265 * Shares the underlying object referenced by the argument by calling ref() on it. If this 266 * sk_sp previously had a reference to an object (i.e. not null) it will call unref() on that 267 * object. 268 */ 269 sk_sp<T>& operator=(const sk_sp<T>& that) { 270 this->reset(SkSafeRef(that.get())); 271 return *this; 272 } 273 template <typename U, typename = skstd::enable_if_t<std::is_convertible<U*, T*>::value>> 274 sk_sp<T>& operator=(const sk_sp<U>& that) { 275 this->reset(SkSafeRef(that.get())); 276 return *this; 277 } 278 279 /** 280 * Move the underlying object from the argument to the sk_sp. If the sk_sp previously held 281 * a reference to another object, unref() will be called on that object. No call to ref() 282 * will be made. 283 */ 284 sk_sp<T>& operator=(sk_sp<T>&& that) { 285 this->reset(that.release()); 286 return *this; 287 } 288 template <typename U, typename = skstd::enable_if_t<std::is_convertible<U*, T*>::value>> 289 sk_sp<T>& operator=(sk_sp<U>&& that) { 290 this->reset(that.release()); 291 return *this; 292 } 293 294 T& operator*() const { 295 SkASSERT(this->get() != nullptr); 296 return *this->get(); 297 } 298 299 // MSVC 2013 does not work correctly with explicit operator bool. 300 // https://chromium-cpp.appspot.com/#core-blacklist 301 // When explicit operator bool can be used, remove operator! and operator unspecified_bool_type. 302 //explicit operator bool() const { return this->get() != nullptr; } 303 operator unspecified_bool_type() const { return this->get() ? &sk_sp::fPtr : nullptr; } 304 bool operator!() const { return this->get() == nullptr; } 305 306 T* get() const { return fPtr; } 307 T* operator->() const { return fPtr; } 308 309 /** 310 * Adopt the new bare pointer, and call unref() on any previously held object (if not null). 311 * No call to ref() will be made. 312 */ 313 void reset(T* ptr = nullptr) { 314 // Calling fPtr->unref() may call this->~() or this->reset(T*). 315 // http://wg21.cmeerw.net/lwg/issue998 316 // http://wg21.cmeerw.net/lwg/issue2262 317 T* oldPtr = fPtr; 318 fPtr = ptr; 319 SkSafeUnref(oldPtr); 320 } 321 322 /** 323 * Return the bare pointer, and set the internal object pointer to nullptr. 324 * The caller must assume ownership of the object, and manage its reference count directly. 325 * No call to unref() will be made. 326 */ 327 T* SK_WARN_UNUSED_RESULT release() { 328 T* ptr = fPtr; 329 fPtr = nullptr; 330 return ptr; 331 } 332 333 void swap(sk_sp<T>& that) /*noexcept*/ { 334 using std::swap; 335 swap(fPtr, that.fPtr); 336 } 337 338private: 339 T* fPtr; 340}; 341 342template <typename T> inline void swap(sk_sp<T>& a, sk_sp<T>& b) /*noexcept*/ { 343 a.swap(b); 344} 345 346template <typename T, typename U> inline bool operator==(const sk_sp<T>& a, const sk_sp<U>& b) { 347 return a.get() == b.get(); 348} 349template <typename T> inline bool operator==(const sk_sp<T>& a, std::nullptr_t) /*noexcept*/ { 350 return !a; 351} 352template <typename T> inline bool operator==(std::nullptr_t, const sk_sp<T>& b) /*noexcept*/ { 353 return !b; 354} 355 356template <typename T, typename U> inline bool operator!=(const sk_sp<T>& a, const sk_sp<U>& b) { 357 return a.get() != b.get(); 358} 359template <typename T> inline bool operator!=(const sk_sp<T>& a, std::nullptr_t) /*noexcept*/ { 360 return static_cast<bool>(a); 361} 362template <typename T> inline bool operator!=(std::nullptr_t, const sk_sp<T>& b) /*noexcept*/ { 363 return static_cast<bool>(b); 364} 365 366template <typename T, typename U> inline bool operator<(const sk_sp<T>& a, const sk_sp<U>& b) { 367 // Provide defined total order on sk_sp. 368 // http://wg21.cmeerw.net/lwg/issue1297 369 // http://wg21.cmeerw.net/lwg/issue1401 . 370 return std::less<skstd::common_type_t<T*, U*>>()(a.get(), b.get()); 371} 372template <typename T> inline bool operator<(const sk_sp<T>& a, std::nullptr_t) { 373 return std::less<T*>()(a.get(), nullptr); 374} 375template <typename T> inline bool operator<(std::nullptr_t, const sk_sp<T>& b) { 376 return std::less<T*>()(nullptr, b.get()); 377} 378 379template <typename T, typename U> inline bool operator<=(const sk_sp<T>& a, const sk_sp<U>& b) { 380 return !(b < a); 381} 382template <typename T> inline bool operator<=(const sk_sp<T>& a, std::nullptr_t) { 383 return !(nullptr < a); 384} 385template <typename T> inline bool operator<=(std::nullptr_t, const sk_sp<T>& b) { 386 return !(b < nullptr); 387} 388 389template <typename T, typename U> inline bool operator>(const sk_sp<T>& a, const sk_sp<U>& b) { 390 return b < a; 391} 392template <typename T> inline bool operator>(const sk_sp<T>& a, std::nullptr_t) { 393 return nullptr < a; 394} 395template <typename T> inline bool operator>(std::nullptr_t, const sk_sp<T>& b) { 396 return b < nullptr; 397} 398 399template <typename T, typename U> inline bool operator>=(const sk_sp<T>& a, const sk_sp<U>& b) { 400 return !(a < b); 401} 402template <typename T> inline bool operator>=(const sk_sp<T>& a, std::nullptr_t) { 403 return !(a < nullptr); 404} 405template <typename T> inline bool operator>=(std::nullptr_t, const sk_sp<T>& b) { 406 return !(nullptr < b); 407} 408 409template <typename T, typename... Args> 410sk_sp<T> sk_make_sp(Args&&... args) { 411 return sk_sp<T>(new T(std::forward<Args>(args)...)); 412} 413 414/* 415 * Returns a sk_sp wrapping the provided ptr AND calls ref on it (if not null). 416 * 417 * This is different than the semantics of the constructor for sk_sp, which just wraps the ptr, 418 * effectively "adopting" it. 419 */ 420template <typename T> sk_sp<T> sk_ref_sp(T* obj) { 421 return sk_sp<T>(SkSafeRef(obj)); 422} 423 424#endif 425