source: Sophya/trunk/SophyaLib/BaseTools/rcptr.h@ 281

Last change on this file since 281 was 281, checked in by ansari, 26 years ago

comptage de refs simple

File size: 1.1 KB
RevLine 
[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
21template <class T>
22class RCPtr {
23public:
24 RCPtr(T* obj) {
25 x = obj;
[281]26 cnt = new int;
27 *cnt = 1;
[280]28 }
29
30 RCPtr(RCPtr<T> const& other) {
31 x = other.x;
[281]32 cnt = other.cnt;
33 (*cnt)++;
[280]34 }
35
36 ~RCPtr() {
[281]37 (*cnt)--;
38 if (!*cnt) {
39 delete x;
40 delete cnt;
[280]41 }
42 }
43
44 T* operator->() {return x;}
45 T& operator*() {return *x;}
46
47private:
48 T* x; // the object we are referring
[281]49 int* cnt; // how many smart pointers ?
[280]50};
51
52#endif
Note: See TracBrowser for help on using the repository browser.