GrNonAtomicRef.h 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /*
  2. * Copyright 2015 Google Inc.
  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 GrNonAtomicRef_DEFINED
  8. #define GrNonAtomicRef_DEFINED
  9. #include "include/core/SkRefCnt.h"
  10. #include "include/private/SkNoncopyable.h"
  11. #include "include/private/SkTArray.h"
  12. /**
  13. * A simple non-atomic ref used in the GrBackendApi when we don't want to pay for the overhead of a
  14. * threadsafe ref counted object
  15. */
  16. template<typename TSubclass> class GrNonAtomicRef : public SkNoncopyable {
  17. public:
  18. GrNonAtomicRef() : fRefCnt(1) {}
  19. #ifdef SK_DEBUG
  20. ~GrNonAtomicRef() {
  21. // fRefCnt can be one when a subclass is created statically
  22. SkASSERT((0 == fRefCnt || 1 == fRefCnt));
  23. // Set to invalid values.
  24. fRefCnt = -10;
  25. }
  26. #endif
  27. bool unique() const { return 1 == fRefCnt; }
  28. void ref() const {
  29. // Once the ref cnt reaches zero it should never be ref'ed again.
  30. SkASSERT(fRefCnt > 0);
  31. ++fRefCnt;
  32. }
  33. void unref() const {
  34. SkASSERT(fRefCnt > 0);
  35. --fRefCnt;
  36. if (0 == fRefCnt) {
  37. GrTDeleteNonAtomicRef(static_cast<const TSubclass*>(this));
  38. return;
  39. }
  40. }
  41. private:
  42. mutable int32_t fRefCnt;
  43. typedef SkNoncopyable INHERITED;
  44. };
  45. template<typename T> inline void GrTDeleteNonAtomicRef(const T* ref) {
  46. delete ref;
  47. }
  48. #endif