Debian Codegraph @

src/af/xap/gtk/xap_GtkObjectHolder.h

raw
1 /* AbiWord
2 * Copyright (C) 2009 Hubert Figuiere
3 *
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation; either version 2
7 * of the License, or (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
17 * 02110-1301 USA.
18 */
19
20
21 #ifndef _XAP_GTKOBJECTHOLDER_H_
22 #define _XAP_GTKOBJECTHOLDER_H_
23
24
25 /** A simple class to hold a scoped ref on a GObject */
26 template <class T>
27 class XAP_GtkObjectHolder
28 {
29 public:
30 XAP_GtkObjectHolder(const XAP_GtkObjectHolder<T> &_obj)
31 : m_obj(_obj.m_obj)
32 {
33 _ref();
34 }
35 XAP_GtkObjectHolder(T * _obj = NULL)
36 : m_obj(_obj)
37 {
38 _ref();
39 }
40 ~XAP_GtkObjectHolder()
41 {
42 _unref();
43 }
44 /// Take the object, without adding a ref.
45 /// The object is now NULL
46 XAP_GtkObjectHolder<T> &take(T *& _obj)
47 {
48 _unref();
49 m_obj = _obj;
50 _obj = nullptr;
51 return *this;
52 }
53 /// Take the object, without adding a ref.
54 /// The object is moved.
55 XAP_GtkObjectHolder<T> &take(T *&& _obj)
56 {
57 _unref();
58 m_obj = _obj;
59 return *this;
60 }
61
62 XAP_GtkObjectHolder<T> & operator=(T * _obj)
63 {
64 _unref();
65 m_obj = _obj;
66 _ref();
67 return *this;
68 }
69 XAP_GtkObjectHolder<T> & operator=(const XAP_GtkObjectHolder<T> & _obj)
70 {
71 _unref();
72 m_obj = _obj.m_obj;
73 _ref();
74 return *this;
75 }
76 T * obj() const
77 {
78 return m_obj;
79 }
80 private:
81 void _unref()
82 {
83 if(m_obj)
84 g_object_unref(m_obj);
85 }
86 void _ref()
87 {
88 if(m_obj)
89 g_object_ref(m_obj);
90 }
91 T* m_obj;
92 };
93
94
95 #endif
96