1 /* 2 * Copyright 2011 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 8 #ifndef SkTScopedComPtr_DEFINED 9 #define SkTScopedComPtr_DEFINED 10 11 #include "src/core/SkLeanWindows.h" 12 #include "src/utils/win/SkObjBase.h" 13 14 #ifdef SK_BUILD_FOR_WIN 15 SkRefComPtr(T * ptr)16template<typename T> T* SkRefComPtr(T* ptr) { 17 ptr->AddRef(); 18 return ptr; 19 } 20 SkSafeRefComPtr(T * ptr)21template<typename T> T* SkSafeRefComPtr(T* ptr) { 22 if (ptr) { 23 ptr->AddRef(); 24 } 25 return ptr; 26 } 27 28 template<typename T> 29 class SkTScopedComPtr { 30 private: 31 T *fPtr; 32 33 public: SkTScopedComPtr()34 constexpr SkTScopedComPtr() : fPtr(nullptr) {} SkTScopedComPtr(std::nullptr_t)35 constexpr SkTScopedComPtr(std::nullptr_t) : fPtr(nullptr) {} SkTScopedComPtr(T * ptr)36 explicit SkTScopedComPtr(T *ptr) : fPtr(ptr) {} SkTScopedComPtr(SkTScopedComPtr && that)37 SkTScopedComPtr(SkTScopedComPtr&& that) : fPtr(that.release()) {} 38 SkTScopedComPtr(const SkTScopedComPtr&) = delete; 39 ~SkTScopedComPtr()40 ~SkTScopedComPtr() { this->reset();} 41 42 SkTScopedComPtr& operator=(SkTScopedComPtr&& that) { 43 this->reset(that.release()); 44 return *this; 45 } 46 SkTScopedComPtr& operator=(const SkTScopedComPtr&) = delete; 47 SkTScopedComPtr& operator=(std::nullptr_t) { this->reset(); return *this; } 48 49 T &operator*() const { SkASSERT(fPtr != nullptr); return *fPtr; } 50 51 explicit operator bool() const { return fPtr != nullptr; } 52 53 T *operator->() const { return fPtr; } 54 55 /** 56 * Returns the address of the underlying pointer. 57 * This is dangerous -- it breaks encapsulation and the reference escapes. 58 * Must only be used on instances currently pointing to NULL, 59 * and only to initialize the instance. 60 */ 61 T **operator&() { SkASSERT(fPtr == nullptr); return &fPtr; } 62 get()63 T *get() const { return fPtr; } 64 65 void reset(T* ptr = nullptr) { 66 if (fPtr) { 67 fPtr->Release(); 68 } 69 fPtr = ptr; 70 } 71 swap(SkTScopedComPtr<T> & that)72 void swap(SkTScopedComPtr<T>& that) { 73 T* temp = this->fPtr; 74 this->fPtr = that.fPtr; 75 that.fPtr = temp; 76 } 77 release()78 T* release() { 79 T* temp = this->fPtr; 80 this->fPtr = nullptr; 81 return temp; 82 } 83 }; 84 85 #endif // SK_BUILD_FOR_WIN 86 #endif // SkTScopedComPtr_DEFINED 87