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_GLIB_UTIL_H_ | |
Lei Zhang
2017/04/06 03:59:54
How about scoped_gobject.h?
Tom (Use chromium acct)
2017/04/06 05:05:35
Done.
| |
6 #define UI_BASE_GLIB_GLIB_UTIL_H_ | |
7 | |
8 #include "base/logging.h" | |
9 | |
10 // Similar in spirit to a std::unique_ptr. | |
11 template <typename T> | |
12 class ScopedGObject { | |
13 public: | |
14 ScopedGObject() : obj_(nullptr) {} | |
15 | |
16 explicit ScopedGObject(T* obj) : obj_(obj) { | |
17 // Remove the floating reference from |obj_| if it has one. | |
18 if (g_object_is_floating(obj_)) | |
19 g_object_ref_sink(obj_); | |
20 DCHECK(G_OBJECT(obj_)->ref_count == 1); | |
21 } | |
22 | |
23 ScopedGObject(const ScopedGObject<T>& other) = delete; | |
24 | |
25 ScopedGObject(ScopedGObject<T>&& other) : obj_(other.obj_) { | |
26 other.obj_ = nullptr; | |
27 } | |
28 | |
29 ~ScopedGObject() { reset(nullptr); } | |
30 | |
31 ScopedGObject<T>& operator=(const ScopedGObject<T>& other) = delete; | |
32 | |
33 ScopedGObject<T>& operator=(ScopedGObject<T>&& other) { | |
34 g_object_unref(obj_); | |
35 obj_ = other.obj_; | |
36 other.obj_ = nullptr; | |
37 return *this; | |
38 } | |
39 | |
40 operator T*() { return obj_; } | |
41 | |
42 void reset(T* obj) { | |
43 if (obj_) | |
44 Unref(); | |
45 obj_ = obj; | |
46 } | |
47 | |
48 private: | |
49 void Unref() { g_object_unref(obj_); } | |
50 | |
51 T* obj_; | |
52 }; | |
53 | |
54 #endif // UI_BASE_GLIB_GLIB_UTIL_H_ | |
OLD | NEW |