Rev | Line | |
---|
[280] | 1 | // This may look like C code, but it is really -*- C++ -*-
|
---|
| 2 |
|
---|
| 3 | #ifndef RCPTR_H
|
---|
| 4 | #define RCPTR_H
|
---|
| 5 |
|
---|
| 6 | // This implements a very simple "smart pointer" with reference counting.
|
---|
| 7 | // Many refinements are possible
|
---|
| 8 | // - const propagation
|
---|
[282] | 9 | // ...
|
---|
[280] | 10 |
|
---|
| 11 | // Principle : use RCPtr<T> instead of T*
|
---|
| 12 | // To use with type X, define
|
---|
| 13 | // typedef RCPtr<X> Xp;
|
---|
| 14 | // When creating a new object, use
|
---|
| 15 | // Xp xp = new X(...);
|
---|
| 16 | // xp can be used like a X* xp->field, xp->method(), *xp ...
|
---|
| 17 | // can be passed by reference, copied, etc
|
---|
| 18 | // the object is destroyed when the last Xp is destroyed.
|
---|
| 19 |
|
---|
| 20 | template <class T>
|
---|
| 21 | class RCPtr {
|
---|
| 22 | public:
|
---|
[282] | 23 | RCPtr(T* obj=0) {
|
---|
[280] | 24 | x = obj;
|
---|
[281] | 25 | cnt = new int;
|
---|
| 26 | *cnt = 1;
|
---|
[280] | 27 | }
|
---|
| 28 |
|
---|
| 29 | RCPtr(RCPtr<T> const& other) {
|
---|
| 30 | x = other.x;
|
---|
[281] | 31 | cnt = other.cnt;
|
---|
| 32 | (*cnt)++;
|
---|
[280] | 33 | }
|
---|
[282] | 34 |
|
---|
| 35 | RCPtr<T>& operator = (RCPtr const& other) {
|
---|
| 36 | (*cnt)--;
|
---|
| 37 | if (!*cnt) {
|
---|
| 38 | delete x;
|
---|
| 39 | delete cnt;
|
---|
| 40 | }
|
---|
| 41 | x = other.x;
|
---|
| 42 | cnt = other.cnt;
|
---|
| 43 | (*cnt)++;
|
---|
| 44 | return *this;
|
---|
| 45 | }
|
---|
[280] | 46 |
|
---|
| 47 | ~RCPtr() {
|
---|
[281] | 48 | (*cnt)--;
|
---|
| 49 | if (!*cnt) {
|
---|
| 50 | delete x;
|
---|
| 51 | delete cnt;
|
---|
[280] | 52 | }
|
---|
| 53 | }
|
---|
| 54 |
|
---|
| 55 | T* operator->() {return x;}
|
---|
| 56 | T& operator*() {return *x;}
|
---|
| 57 |
|
---|
| 58 | private:
|
---|
| 59 | T* x; // the object we are referring
|
---|
[281] | 60 | int* cnt; // how many smart pointers ?
|
---|
[280] | 61 | };
|
---|
| 62 |
|
---|
| 63 | #endif
|
---|
Note:
See
TracBrowser
for help on using the repository browser.