File: shared_ptr.h

package info (click to toggle)
indigo 1.2.3-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 28,256 kB
  • sloc: ansic: 309,316; cpp: 137,636; cs: 9,118; asm: 8,011; java: 7,195; sql: 6,697; xml: 4,352; python: 3,426; sh: 207; php: 56; makefile: 49
file content (108 lines) | stat: -rw-r--r-- 1,566 bytes parent folder | download | duplicates (5)
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
106
107
108
#ifndef __shared_ptr__
#define __shared_ptr__

#include "base_cpp/exception.h"
#include "base_cpp/red_black.h"
#include "base_cpp/os_sync_wrapper.h"

namespace indigo
{

class SharedPtrStaticData
{
protected:
   static RedBlackMap<void *, int> _counters;
   static OsLock _lock;
};

DECL_EXCEPTION(SharedPtrError);

template <typename T> class SharedPtr : public SharedPtrStaticData
{
public:
   explicit SharedPtr (T *ptr = 0)
   {
      _ptr = ptr;
      _capture();
   }

   ~SharedPtr ()
   {
      _release();
   }

   T * get () const
   {
      return _ptr;
   }

   T & ref () const
   {
      if (_ptr == 0)
         throw Error("no reference");

      return *_ptr;
   }

   T * operator -> () const
   {
      if (_ptr == 0)
         throw Error("no reference");

      return _ptr;
   }

   void reset (T *ptr)
   {
      if (ptr != _ptr)
      {
         _release();
         _ptr = ptr;
         _capture();
      }
   }

   DECL_TPL_ERROR(SharedPtrError);

protected:
   void _release ()
   {
      OsLocker locker(_lock);

      if (_ptr == 0)
         return;

      int &counter = _counters.at(_ptr);

      counter--;
      if (counter == 0)
      {
         _counters.remove(_ptr);
         delete _ptr;
      }
}

   void _capture ()
   {
      OsLocker locker(_lock);

      if (_ptr == 0)
         return;

      int *counter = _counters.at2(_ptr);

      if (counter == 0)
         _counters.insert(_ptr, 1);
      else
         (*counter)++;
   }

   T *_ptr;
   
private:
   SharedPtr (const SharedPtr &); // no implicit copy
};

}

#endif