summaryrefslogtreecommitdiff
path: root/chromium/ui/base/glib/scoped_gobject.h
blob: 24ef91ec9be6a65fd8ae328c5e31dfa02bbbf17e (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
57
58
59
60
// Copyright 2017 The Chromium 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 UI_BASE_GLIB_SCOPED_GOBJECT_H_
#define UI_BASE_GLIB_SCOPED_GOBJECT_H_

// Similar in spirit to a std::unique_ptr.
template <typename T>
class ScopedGObject {
 public:
  ScopedGObject() : obj_(nullptr) {}

  explicit ScopedGObject(T* obj) : obj_(obj) { Ref(); }

  ScopedGObject(const ScopedGObject<T>& other) = delete;

  ScopedGObject(ScopedGObject<T>&& other) : obj_(other.obj_) {
    other.obj_ = nullptr;
  }

  ~ScopedGObject() { reset(); }

  ScopedGObject<T>& operator=(const ScopedGObject<T>& other) = delete;

  ScopedGObject<T>& operator=(ScopedGObject<T>&& other) {
    reset();
    obj_ = other.obj_;
    other.obj_ = nullptr;
    return *this;
  }

  T* get() { return obj_; }

  operator T*() { return obj_; }

  void reset(T* obj = nullptr) {
    Unref();
    obj_ = obj;
    Ref();
  }

 private:
  void Ref() {
    // Remove the floating reference from |obj_| if it has one.
    if (obj_ && g_object_is_floating(obj_))
      g_object_ref_sink(obj_);
  }

  // This function is necessary so that gtk can overload it in
  // the case of T = GtkStyleContext.
  void Unref() {
    if (obj_)
      g_object_unref(obj_);
  }

  T* obj_;
};

#endif  // UI_BASE_GLIB_SCOPED_GOBJECT_H_