libshevek
refbase.hh
1 /* refbase.hh - base class for using Glib::RefPtr
2  * Copyright 2003 Bas Wijnen <wijnen@debian.org>
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (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, see <http://www.gnu.org/licenses/>.
16  */
17 
18 #ifndef SHEVEK_REFBASE_HH
19 #define SHEVEK_REFBASE_HH
20 
21 #include <sigc++/sigc++.h>
22 #include <glibmm/refptr.h>
23 
24 namespace shevek
25 {
27  class refbase
28  {
29  public:
31  template <typename _T> Glib::RefPtr <_T> cast_dynamic ()
32  { return Glib::RefPtr <_T>::cast_dynamic (refptr_this <refbase> ()); }
33  protected:
35  refbase ();
37  virtual ~refbase ();
39 
42  template <typename T> Glib::RefPtr <T> refptr_this ();
43  private:
44  // Not copyable
45  refbase (refbase const &that);
46  refbase &operator= (refbase const &that);
47  // Reference functions, needed for Glib::RefPtr.
48  virtual void reference ();
49  virtual void unreference ();
50  // Allow Glib::RefPtr to call the above.
51  template <typename T> friend class Glib::RefPtr;
52  // Reference count.
53  unsigned m_refcount;
54  };
55 
56  template <typename T>
57  Glib::RefPtr <T> refbase::refptr_this ()
58  {
59  // This is a bit of a hack, but I don't see a way to solve it otherwise.
60  // The idea is that members of refbase-derived classes need a refptr to
61  // their this pointer, to give away.
62  // The only usable constructor of RefPtr for that purpose is the one which
63  // is meant for create (). However, that does not increment the reference
64  // counter. So I do that by hand.
65  reference ();
66  return Glib::RefPtr <T> (dynamic_cast <T *> (this) );
67  }
68 }
69 
70 #endif
Base class for classes which want reference counting through Glib::RefPtr.
Definition: refbase.hh:27
Definition: args.hh:52
Glib::RefPtr< _T > cast_dynamic()
Identical to GLib::RefPtr <>::cast_dynamic, but nicer to type.
Definition: refbase.hh:31
refbase()
Constructor, increments reference count.
virtual ~refbase()
Destructor, decrements reference count and destroys the object if it reaches 0.
Glib::RefPtr< T > refptr_this()
Get a RefPtr to this, protected because only members should need it.
Definition: refbase.hh:57