summaryrefslogtreecommitdiff
path: root/libcult/cult/mm/bits/shptr.hxx
blob: 7089c5350dabea14eaf28d84c4528b430b03e9d2 (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
// file      : cult/mm/bits/shptr.hxx
// author    : Boris Kolpackov <boris@kolpackov.net>
// copyright : Copyright (c) 2005-2010 Boris Kolpackov
// license   : GNU GPL v2 + exceptions; see accompanying LICENSE file

#ifndef CULT_MM_BITS_SHPTR_HXX
#define CULT_MM_BITS_SHPTR_HXX

#include <cult/types/fundamental.hxx>

#include <cult/mm/counter.hxx>
#include <cult/mm/exception.hxx>

namespace Cult
{
  namespace MM
  {
    namespace Bits
    {
      template <typename X>
      class Shptr
      {
      protected:
        ~Shptr ()
        {
          if (c_ && c_->dec_ref ()) delete p_;
        }

        Shptr (X* p, Counter* c, Boolean inc = true)
            : p_ (p), c_ (c)
        {
          if (c_ && inc) c_->inc_ref ();
        }

      protected:
        X*
        release_ () throw ()
        {
          X* tmp (p_);

          c_ = 0;
          p_ = 0;

          return tmp;
        }

      protected:
        template<typename y>
        Void
        assign (Shptr<y> const& bp, Boolean inc = true)
        {
          assign (bp.p_, bp.c_, inc);
        }

        Void
        assign (X* p, Counter* c, Boolean inc)
        {
          if (c_ && c_ == c) throw SelfAssignment ();

          if (c_)
          {
            Counter* t (c_);
            c_ = 0;
            p_ = 0;
            t->dec_ref ();
          }

          if (c && inc) c->inc_ref ();

          p_ = p;
          c_ = c;
        }

      protected:
        template <typename>
        friend class Shptr;

        X* p_;
        Counter* c_;
      };
    }
  }
}

#endif  // CULT_MM_BITS_SHPTR_HXX