Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

some WeaponManager remake

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 = 0) // allocate a new counter
12        : itsCounter(0) { 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            release();
19            acquire(r.itsCounter);
20        }
21        return *this;
22    }
23    X& operator*()  const { return *itsCounter->ptr; }
24    X* operator->() const { return itsCounter->ptr; }
25    X* get()        const { return itsCounter ? itsCounter->ptr : 0; }
26    bool unique()   const { return (itsCounter ? itsCounter->count == 1 : true); }
27    virtual unsigned int count() const { return (this->itsCounter ? itsCounter->count : 0); }
28private:
29
30    struct counter {
31        counter(X* p = 0, unsigned c = 1) : ptr(p), count(c) {}
32        X*          ptr;
33        unsigned    count;
34    }* itsCounter;
35
36    void acquire(counter* c)
37    {
38      // increment the count
39        itsCounter = c;
40        if (c) ++c->count;
41    }
42
43    void release()
44    {
45      // decrement the count, delete if it is 0
46        if (itsCounter) {
47            if (--itsCounter->count == 0) {
48                delete itsCounter->ptr;
49                delete itsCounter;
50            }
51            itsCounter = 0;
52        }
53    }
54};
55
56#endif /* _COUNT_POINTER_H */
Note: See TracBrowser for help on using the repository browser.