Index: ui/base/glib/scoped_gobject.h |
diff --git a/ui/base/glib/scoped_gobject.h b/ui/base/glib/scoped_gobject.h |
new file mode 100644 |
index 0000000000000000000000000000000000000000..702144e39c90fc0cde0e21a472c58279850a1649 |
--- /dev/null |
+++ b/ui/base/glib/scoped_gobject.h |
@@ -0,0 +1,54 @@ |
+// 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_ |
+ |
+#include "base/logging.h" |
+ |
+// Similar in spirit to a std::unique_ptr. |
+template <typename T> |
+class ScopedGObject { |
+ public: |
+ ScopedGObject() : obj_(nullptr) {} |
+ |
+ explicit ScopedGObject(T* obj) : obj_(obj) { |
+ // Remove the floating reference from |obj_| if it has one. |
sky
2017/04/06 20:44:46
Should reset() get this logic too? If not, why?
Tom (Use chromium acct)
2017/04/06 22:28:57
Yes it should! Thanks for catching this!
|
+ if (g_object_is_floating(obj_)) |
+ g_object_ref_sink(obj_); |
+ DCHECK(G_OBJECT(obj_)->ref_count == 1); |
+ } |
+ |
+ 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) { |
+ g_object_unref(obj_); |
sky
2017/04/06 20:44:46
reset() ?
Tom (Use chromium acct)
2017/04/06 22:28:57
Done.
|
+ obj_ = other.obj_; |
+ other.obj_ = nullptr; |
+ return *this; |
+ } |
+ |
+ operator T*() { return obj_; } |
+ |
+ void reset(T* obj = nullptr) { |
+ if (obj_) |
+ Unref(); |
sky
2017/04/06 20:44:46
It's mildly confusing that you have both reset and
Tom (Use chromium acct)
2017/04/06 22:28:57
Can't unfortunately. We require a template overri
sky
2017/04/06 23:30:17
Subtle! Please add a comment about that as it's ea
|
+ obj_ = obj; |
+ } |
+ |
+ private: |
+ void Unref() { g_object_unref(obj_); } |
+ |
+ T* obj_; |
+}; |
+ |
+#endif // UI_BASE_GLIB_SCOPED_GOBJECT_H_ |