Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/branches/proxy/src/lib/util/count_pointer.h @ 9442

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

merged the new Font-Implementation back here
merged with svn merge https://svn.orxonox.net/orxonox/branches/fontdata . -r8752:HEAD
no conflicts, naturally

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