Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/trunk/src/lib/util/count_pointer.h @ 10510

Last change on this file since 10510 was 9869, checked in by bensch, 18 years ago

orxonox/trunk: merged the new_class_id branche back to the trunk.
merged with command:
svn merge https://svn.orxonox.net/orxonox/branches/new_class_id trunk -r9683:HEAD
no conflicts… puh..

File size: 1.5 KB
Line 
1/*!
2 * @file count_pointer.h Contains the Counted Pointer Class, that points to Member-Objects.
3 */
4
5#ifndef _COUNT_POINTER_H
6#define _COUNT_POINTER_H
7
8template <typename X> class CountPointer
9{
10public:
11  explicit CountPointer(X* p = NULL) // allocate a new counter
12      : itsCounter(NULL) { if (p) itsCounter = new counter(p); }
13  ~CountPointer() { release(); }
14  CountPointer(const CountPointer& r) { acquire(r.itsCounter); }
15  CountPointer& operator=(const CountPointer& r)
16  {
17    if (this != &r)
18    {
19      release();
20      acquire(r.itsCounter);
21    }
22    return *this;
23  }
24  bool operator==(const CountPointer& r) const { return this->itsCounter->ptr == r.itsCounter->ptr; };
25  inline X& operator*()  const { return *itsCounter->ptr; }
26  inline X* operator->() const { return itsCounter->ptr; }
27  inline bool unique()   const { return (itsCounter ? itsCounter->count == 1 : true); }
28  inline bool isNull()   const { return (!itsCounter); }
29
30  unsigned int count() const { return (this->itsCounter ? itsCounter->count : 0); }
31private:
32
33  struct counter
34  {
35    counter(X* p = NULL, unsigned c = 1) : ptr(p), count(c) {}
36    X*          ptr;
37    unsigned    count;
38  }
39  * itsCounter;
40
41  void acquire(counter* c)
42  {
43    // increment the count
44    itsCounter = c;
45    if (c) ++c->count;
46  }
47
48  void release()
49  {
50    // decrement the count, delete if it is 0
51    if (itsCounter)
52    {
53      if (--itsCounter->count == 0)
54      {
55        delete itsCounter->ptr;
56        delete itsCounter;
57      }
58      itsCounter = NULL;
59    }
60  }
61};
62
63#endif /* _COUNT_POINTER_H */
Note: See TracBrowser for help on using the repository browser.