blob: 85c314a97ae04ba3a6591ccc12c9d0572bbb3a63 [file] [log] [blame]
epoger@google.comec3ed6a2011-07-28 14:26:00 +00001
bungeman@google.com9df621d2011-06-23 21:43:52 +00002/*
epoger@google.comec3ed6a2011-07-28 14:26:00 +00003 * Copyright 2011 Google Inc.
4 *
5 * Use of this source code is governed by a BSD-style license that can be
6 * found in the LICENSE file.
bungeman@google.com9df621d2011-06-23 21:43:52 +00007 */
8
bungeman@google.com9df621d2011-06-23 21:43:52 +00009#ifndef SkSkTScopedPtr_DEFINED
10#define SkSkTScopedPtr_DEFINED
11
bungeman@google.comb29c8832011-10-10 13:19:10 +000012#include "SkTypes.h"
bungeman@google.com9df621d2011-06-23 21:43:52 +000013#include "SkTemplates.h"
14
15template<typename T>
bungeman@google.comb29c8832011-10-10 13:19:10 +000016class SkBlockComRef : public T {
17private:
18 virtual ULONG STDMETHODCALLTYPE AddRef(void) = 0;
19 virtual ULONG STDMETHODCALLTYPE Release(void) = 0;
20};
21
22template<typename T>
bungeman@google.com9df621d2011-06-23 21:43:52 +000023class SkTScopedComPtr : SkNoncopyable {
24private:
25 T *fPtr;
26
27public:
28 explicit SkTScopedComPtr(T *ptr = NULL) : fPtr(ptr) { }
29 ~SkTScopedComPtr() {
bungeman@google.coma9e586a2011-08-09 19:25:05 +000030 this->reset();
bungeman@google.com9df621d2011-06-23 21:43:52 +000031 }
bungeman@google.come8f05922012-08-16 16:13:40 +000032 T &operator*() const { SkASSERT(fPtr != NULL); return *fPtr; }
bungeman@google.comb29c8832011-10-10 13:19:10 +000033 SkBlockComRef<T> *operator->() const {
34 return static_cast<SkBlockComRef<T>*>(fPtr);
35 }
bungeman@google.com9df621d2011-06-23 21:43:52 +000036 /**
37 * Returns the address of the underlying pointer.
38 * This is dangerous -- it breaks encapsulation and the reference escapes.
39 * Must only be used on instances currently pointing to NULL,
40 * and only to initialize the instance.
41 */
42 T **operator&() { SkASSERT(fPtr == NULL); return &fPtr; }
43 T *get() const { return fPtr; }
bungeman@google.coma9e586a2011-08-09 19:25:05 +000044 void reset() {
45 if (NULL != this->fPtr) {
46 this->fPtr->Release();
47 this->fPtr = NULL;
48 }
49 }
rmistry@google.comfbfcd562012-08-23 18:09:54 +000050
bungeman@google.comb29c8832011-10-10 13:19:10 +000051 void swap(SkTScopedComPtr<T>& that) {
52 T* temp = this->fPtr;
53 this->fPtr = that.fPtr;
54 that.fPtr = temp;
55 }
rmistry@google.comfbfcd562012-08-23 18:09:54 +000056
bungeman@google.comb29c8832011-10-10 13:19:10 +000057 T* release() {
58 T* temp = this->fPtr;
59 this->fPtr = NULL;
60 return temp;
61 }
bungeman@google.com9df621d2011-06-23 21:43:52 +000062};
63
64#endif