[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 | // - implement operator =
|
---|
| 9 | // - const propagation
|
---|
| 10 | // - invasive, when type T has field refcnt, instead of list
|
---|
| 11 |
|
---|
| 12 | // Principle : use RCPtr<T> instead of T*
|
---|
| 13 | // To use with type X, define
|
---|
| 14 | // typedef RCPtr<X> Xp;
|
---|
| 15 | // When creating a new object, use
|
---|
| 16 | // Xp xp = new X(...);
|
---|
| 17 | // xp can be used like a X* xp->field, xp->method(), *xp ...
|
---|
| 18 | // can be passed by reference, copied, etc
|
---|
| 19 | // the object is destroyed when the last Xp is destroyed.
|
---|
| 20 |
|
---|
| 21 | #include <list>
|
---|
| 22 |
|
---|
| 23 | template <class T>
|
---|
| 24 | class RCPtr {
|
---|
| 25 | public:
|
---|
| 26 | RCPtr(T* obj) {
|
---|
| 27 | x = obj;
|
---|
| 28 | }
|
---|
| 29 |
|
---|
| 30 | RCPtr(RCPtr<T> const& other) {
|
---|
| 31 | peers = other.peers;
|
---|
| 32 | x = other.x;
|
---|
| 33 | peers.push_back((RCPtr<T>*)&other);
|
---|
| 34 | for (peerlist::iterator i = peers.begin();
|
---|
| 35 | i != peers.end(); i++) {
|
---|
| 36 | (*i)->hello(this);
|
---|
| 37 | }
|
---|
| 38 | }
|
---|
| 39 |
|
---|
| 40 | ~RCPtr() {
|
---|
| 41 | for (peerlist::iterator i = peers.begin();
|
---|
| 42 | i != peers.end(); i++) {
|
---|
| 43 | (*i)->byebye(this);
|
---|
| 44 | }
|
---|
| 45 | if (peers.size() == 0) delete x;
|
---|
| 46 | }
|
---|
| 47 |
|
---|
| 48 | T* operator->() {return x;}
|
---|
| 49 | T& operator*() {return *x;}
|
---|
| 50 |
|
---|
| 51 | private:
|
---|
| 52 | typedef list<RCPtr<T>*> peerlist;
|
---|
| 53 |
|
---|
| 54 | T* x; // the object we are referring
|
---|
| 55 | peerlist peers; // the other smart pointers to the same object
|
---|
| 56 |
|
---|
| 57 | void hello(RCPtr<T>* newcomer) {
|
---|
| 58 | peers.push_back(newcomer);
|
---|
| 59 | }
|
---|
| 60 |
|
---|
| 61 | void byebye(RCPtr<T>* dying) {
|
---|
| 62 | peers.remove(dying);
|
---|
| 63 | }
|
---|
| 64 | };
|
---|
| 65 |
|
---|
| 66 | #endif
|
---|