Coda Distributed File System
refcounted.h
Go to the documentation of this file.
1/* BLURB gpl
2
3 Coda File System
4 Release 6
5
6 Copyright (c) 2003 Carnegie Mellon University
7 Additional copyrights listed below
8
9This code is distributed "AS IS" without warranty of any kind under
10the terms of the GNU General Public Licence Version 2, as shown in the
11file LICENSE. The technical and financial contributors to Coda are
12listed in the file CREDITS.
13
14 Additional copyrights
15 none currently
16#*/
17
18/*
19 * Base class that implements refcounting. Useable for VM objects that can be
20 * referenced from different places and should be automatically destroyed when
21 * the last reference is dropped
22 */
23
24#ifndef _REFCOUNTED_H_
25#define _REFCOUNTED_H_
26
27#ifdef __cplusplus
28extern "C" {
29#endif
30
31#include <stdio.h>
32#include <assert.h>
33
34#ifdef __cplusplus
35}
36#endif
37
39protected:
40 unsigned int refcount;
41
42 /* Creation grabs an implicit reference */
44
45 /* Deletion is ok when the refcount is either 0 or 1.
46 * i.e. when it is one `delete' is similar to `PutRef', but PutRef is
47 * still preferred */
48 virtual ~RefCountedObject() { assert(refcount <= 1); }
49
50public:
51 /* Grab a reference to the object */
52 void GetRef(void) { refcount++; }
53
54 /* Put a reference, destroying the object when the last reference is put */
55 void PutRef(void)
56 {
57 assert(refcount > 0);
58 if (!(--refcount))
59 delete this;
60 }
61
62 /* Print the current reference count */
63 void PrintRef(FILE *f) { fprintf(f, "\trefcount %u\n", refcount); }
64};
65
66#ifdef TESTING
67/* some code to test the functionality of a RefCountedObject */
68class RefObj : public RefCountedObject {
69public:
70 RefObj() { printf("Creating RefObj\n"); };
71 ~RefObj() { printf("Destroying RefObj\n"); };
72};
73
74void main(void)
75{
76 RefObj *test = new RefObj;
77
78 printf("New object refcnt should be 1\n");
79 test->PrintRef(stdout);
80 test->GetRef();
81 printf("Got a reference refcnt should be 2\n");
82 test->PrintRef(stdout);
83 test->PutRef();
84 printf("Dropped a reference refcnt should be 1\n");
85 test->PrintRef(stdout);
86 test->PutRef();
87 printf("Dropped a reference Object should be destroyed\n");
88 printf("Done");
89}
90#endif
91#endif /* _REFCOUNTED_H_ */
int main(int argc, char *argv[])
Definition: altest.c:105
Definition: refcounted.h:38
void GetRef(void)
Definition: refcounted.h:52
virtual ~RefCountedObject()
Definition: refcounted.h:48
void PrintRef(FILE *f)
Definition: refcounted.h:63
RefCountedObject()
Definition: refcounted.h:43
unsigned int refcount
Definition: refcounted.h:40
void PutRef(void)
Definition: refcounted.h:55
printf("Looking at directory %s \n", argv[1])
stdout
Definition: volusage.py:12
@ f
Definition: rvm_private.h:416
assert(SDesc->Tag==SMARTFTP)
fprintf(outFile, "Tag: SMARTFTP\n")