SkRefCnt.h 14 KB

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