summaryrefslogtreecommitdiff
path: root/core/fxcrt/cfx_retain_ptr.h
blob: 883494e7eceb432b4fc2eeeb3cc94260e2c2496d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// Copyright 2016 PDFium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef CORE_FXCRT_CFX_RETAIN_PTR_H_
#define CORE_FXCRT_CFX_RETAIN_PTR_H_

#include <memory>

#include "core/fxcrt/fx_memory.h"

template <class T>
class CFX_RetainPtr {
 public:
  explicit CFX_RetainPtr(T* pObj) : m_pObj(pObj) {
    if (m_pObj)
      m_pObj->Retain();
  }

  CFX_RetainPtr() : CFX_RetainPtr(nullptr) {}
  CFX_RetainPtr(const CFX_RetainPtr& that) : CFX_RetainPtr(that.Get()) {}
  CFX_RetainPtr(CFX_RetainPtr&& that) { Swap(that); }

  template <class U>
  CFX_RetainPtr(const CFX_RetainPtr<U>& that) : CFX_RetainPtr(that.Get()) {}

  void Reset(T* obj = nullptr) {
    if (obj)
      obj->Retain();
    m_pObj.reset(obj);
  }

  T* Get() const { return m_pObj.get(); }
  void Swap(CFX_RetainPtr& that) { m_pObj.swap(that.m_pObj); }

  CFX_RetainPtr& operator=(const CFX_RetainPtr& that) {
    if (*this != that)
      Reset(that.Get());
    return *this;
  }

  bool operator==(const CFX_RetainPtr& that) const {
    return Get() == that.Get();
  }

  bool operator!=(const CFX_RetainPtr& that) const { return !(*this == that); }

  explicit operator bool() const { return !!m_pObj; }
  T& operator*() const { return *m_pObj.get(); }
  T* operator->() const { return m_pObj.get(); }

 private:
  std::unique_ptr<T, ReleaseDeleter<T>> m_pObj;
};

#endif  // CORE_FXCRT_CFX_RETAIN_PTR_H_