summaryrefslogtreecommitdiff
path: root/contrib/utility/Utility/ReferenceCounting/DefaultImpl.ipp
blob: bac28c77ea232fdb6c4cdef70242c8d8d2a0c97e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
// file      : Utility/ReferenceCounting/DefaultImpl.ipp
// author    : Boris Kolpackov <boris@kolpackov.net>
// copyright : Copyright (c) 2002-2003 Boris Kolpackov
// license   : http://kolpackov.net/license.html

namespace Utility
{
  namespace ReferenceCounting
  {
    // c-tor & d-tor

    template <typename SynchPolicy>
    DefaultImpl<SynchPolicy>::
    DefaultImpl () throw (Interface::SystemException)
        : ref_count_ (1),
          lock_ ()
    {
    }

    template <typename SynchPolicy>
    DefaultImpl<SynchPolicy>::
    ~DefaultImpl () throw ()
    {
    }

    // add_ref, remove_ref and refcount_value member functions

    template <typename SynchPolicy>
    void DefaultImpl<SynchPolicy>::
    add_ref () const throw (Exception, SystemException)
    {
      WriteGuard_ guard (lock_);
      add_ref_i ();
    }

    template <typename SynchPolicy>
    void DefaultImpl<SynchPolicy>::
    remove_ref () const throw ()
    {
      bool destroy (false);
      try
      {
        WriteGuard_ guard (lock_);
        destroy = remove_ref_i ();
      }
      catch (...)
      {
        // there is nothing we can do
      }

      if (destroy) delete this;
    }

    template <typename SynchPolicy>
    Interface::count_t DefaultImpl<SynchPolicy>::
    refcount_value () const throw (Exception, SystemException)
    {
      ReadGuard_ guard (lock_);
      return refcount_value_i ();
    }

    // add_ref_i, remove_ref_i and refcount_value_i member functions

    template <typename SynchPolicy>
    void DefaultImpl<SynchPolicy>::
    add_ref_i () const throw (Exception, SystemException)
    {
      ref_count_++;
    }

    template <typename SynchPolicy>
    bool DefaultImpl<SynchPolicy>::
    remove_ref_i () const throw (Exception, SystemException)
    {
      bool destroy (false);
      if (ref_count_ > 0)
      {
        if (--ref_count_ == 0) destroy = true;
      }
      else
      {
        throw InconsistentState (
          "Utility::ReferenceCounting::DefaultImpl::_remove_ref_i: "
          "reference counter is zero.");
      }
      return destroy;

    }

    template <typename SynchPolicy>
    Interface::count_t DefaultImpl<SynchPolicy>::
    refcount_value_i () const throw (Exception, SystemException)
    {
      return ref_count_;
    }

    template <typename SynchPolicy>
    typename SynchPolicy::Mutex& DefaultImpl<SynchPolicy>::
    lock_i() const throw ()
    {
      return lock_;
    }
  }
}
//$Id$