Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

Last change on this file since 8290 was 8145, checked in by bensch, 19 years ago

trunk: merged the gui back
merged with command:
svn merge -r8114:HEAD https://svn.orxonox.net/orxonox/branches/gui .
→ no conflicts

File size: 1.5 KB
RevLine 
[6669]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); }
[8145]13    virtual ~CountPointer() { release(); }
[6669]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.