Home | History | Annotate | Download | only in sdk_util
      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:
     17   ScopedRefBase() : ptr_(NULL) {}
     18   ~ScopedRefBase() { reset(NULL); }
     19 
     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:
     37   ScopedRef() {}
     38   ScopedRef(const ScopedRef& ptr) { reset(ptr.get()); }
     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>
     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); }
     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;
     76   void bool_as_func_impl() const {};
     77 
     78  public:
     79   operator bool_as_func_ptr() const {
     80     return (ptr_ != NULL) ? &ScopedRef::bool_as_func_impl : 0;
     81   }
     82 };
     83 
     84 }  // namespace sdk_util
     85 
     86 #endif  // LIBRARIES_SDK_UTIL_SCOPED_REF_H_
     87