OLD | NEW |
(Empty) | |
| 1 // Copyright 2017 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 UI_BASE_GLIB_SCOPED_GOBJECT_H_ |
| 6 #define UI_BASE_GLIB_SCOPED_GOBJECT_H_ |
| 7 |
| 8 // Similar in spirit to a std::unique_ptr. |
| 9 template <typename T> |
| 10 class ScopedGObject { |
| 11 public: |
| 12 ScopedGObject() : obj_(nullptr) {} |
| 13 |
| 14 explicit ScopedGObject(T* obj) : obj_(obj) { Ref(); } |
| 15 |
| 16 ScopedGObject(const ScopedGObject<T>& other) = delete; |
| 17 |
| 18 ScopedGObject(ScopedGObject<T>&& other) : obj_(other.obj_) { |
| 19 other.obj_ = nullptr; |
| 20 } |
| 21 |
| 22 ~ScopedGObject() { reset(); } |
| 23 |
| 24 ScopedGObject<T>& operator=(const ScopedGObject<T>& other) = delete; |
| 25 |
| 26 ScopedGObject<T>& operator=(ScopedGObject<T>&& other) { |
| 27 reset(); |
| 28 obj_ = other.obj_; |
| 29 other.obj_ = nullptr; |
| 30 return *this; |
| 31 } |
| 32 |
| 33 operator T*() { return obj_; } |
| 34 |
| 35 void reset(T* obj = nullptr) { |
| 36 Unref(); |
| 37 obj_ = obj; |
| 38 Ref(); |
| 39 } |
| 40 |
| 41 private: |
| 42 void Ref() { |
| 43 // Remove the floating reference from |obj_| if it has one. |
| 44 if (obj_ && g_object_is_floating(obj_)) |
| 45 g_object_ref_sink(obj_); |
| 46 } |
| 47 |
| 48 // This function is necessary so that libgtkui can overload it in |
| 49 // the case of T = GtkStyleContext. |
| 50 void Unref() { |
| 51 if (obj_) |
| 52 g_object_unref(obj_); |
| 53 } |
| 54 |
| 55 T* obj_; |
| 56 }; |
| 57 |
| 58 #endif // UI_BASE_GLIB_SCOPED_GOBJECT_H_ |
OLD | NEW |