• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef LIBRARIES_SDK_UTIL_SCOPED_REF_H_
6 #define LIBRARIES_SDK_UTIL_SCOPED_REF_H_
7 
8 #include <stdlib.h>
9 
10 #include "sdk_util/macros.h"
11 #include "sdk_util/ref_object.h"
12 
13 namespace sdk_util {
14 
15 class ScopedRefBase {
16  protected:
ScopedRefBase()17   ScopedRefBase() : ptr_(NULL) {}
~ScopedRefBase()18   ~ScopedRefBase() { reset(NULL); }
19 
reset(RefObject * obj)20   void reset(RefObject* obj) {
21     if (obj) {
22       obj->Acquire();
23     }
24     if (ptr_) {
25       ptr_->Release();
26     }
27     ptr_ = obj;
28   }
29 
30  protected:
31   RefObject* ptr_;
32 };
33 
34 template <class T>
35 class ScopedRef : public ScopedRefBase {
36  public:
ScopedRef()37   ScopedRef() {}
ScopedRef(const ScopedRef & ptr)38   ScopedRef(const ScopedRef& ptr) { reset(ptr.get()); }
ScopedRef(T * ptr)39   explicit ScopedRef(T* ptr) { reset(ptr); }
40 
41   ScopedRef& operator=(const ScopedRef& ptr) {
42     reset(ptr.get());
43     return *this;
44   }
45 
46   template <typename U>
ScopedRef(const ScopedRef<U> & ptr)47   ScopedRef(const ScopedRef<U>& ptr) {
48     reset(ptr.get());
49   }
50 
51   template <typename U>
52   ScopedRef& operator=(const ScopedRef<U>& ptr) {
53     reset(ptr.get());
54     return *this;
55   }
56 
57   void reset(T* obj = NULL) { ScopedRefBase::reset(obj); }
get()58   T* get() const { return static_cast<T*>(ptr_); }
59 
60   template <typename U>
61   bool operator==(const ScopedRef<U>& p) const {
62     return get() == p.get();
63   }
64 
65   template <typename U>
66   bool operator!=(const ScopedRef<U>& p) const {
67     return get() != p.get();
68   }
69 
70  public:
71   T& operator*() const { return *get(); }
72   T* operator->() const { return get(); }
73 
74  private:
75   typedef void (ScopedRef::*bool_as_func_ptr)() const;
bool_as_func_impl()76   void bool_as_func_impl() const {};
77 
78  public:
bool_as_func_ptr()79   operator bool_as_func_ptr() const {
80     return (ptr_ != NULL) ? &ScopedRef::bool_as_func_impl : 0;
81   }
82 };
83 
84 template <typename U, typename T>
static_scoped_ref_cast(const ScopedRef<T> & ptr)85 ScopedRef<U> static_scoped_ref_cast(const ScopedRef<T>& ptr) {
86   return ScopedRef<U>(static_cast<U*>(ptr.get()));
87 }
88 
89 }  // namespace sdk_util
90 
91 #endif  // LIBRARIES_SDK_UTIL_SCOPED_REF_H_
92