]> git.ipfire.org Git - thirdparty/squid.git/blob - src/base/TidyPointer.h
SourceFormat Enforcement
[thirdparty/squid.git] / src / base / TidyPointer.h
1 /*
2 * Copyright (C) 1996-2015 The Squid Software Foundation and contributors
3 *
4 * Squid software is distributed under GPLv2+ license and includes
5 * contributions from numerous individuals and organizations.
6 * Please see the COPYING and CONTRIBUTORS files for details.
7 */
8
9 #ifndef SQUID_BASE_TIDYPOINTER_H
10 #define SQUID_BASE_TIDYPOINTER_H
11
12 /**
13 * A pointer that deletes the object it points to when the pointer's owner or
14 * context is gone. Similar to std::auto_ptr but without confusing assignment
15 * and with a customizable cleanup method. Prevents memory leaks in
16 * the presence of exceptions and processing short cuts.
17 */
18 template <typename T, void (*DeAllocator)(T *t)> class TidyPointer
19 {
20 public:
21 /// Delete callback.
22 typedef void DCB (T *t);
23 TidyPointer(T *t = NULL)
24 : raw(t) {}
25 public:
26 bool operator !() const { return !raw; }
27 /// Returns raw and possibly NULL pointer
28 T *get() const { return raw; }
29 /// Address of the raw pointer, for pointer-setting functions
30 T **addr() { return &raw; }
31 /// Reset raw pointer - delete last one and save new one.
32 void reset(T *t) {
33 deletePointer();
34 raw = t;
35 }
36
37 /// Forget the raw pointer without freeing it. Become a nil pointer.
38 T *release() {
39 T *ret = raw;
40 raw = NULL;
41 return ret;
42 }
43 /// Deallocate raw pointer.
44 ~TidyPointer() {
45 deletePointer();
46 }
47 private:
48 /// Forbidden copy constructor.
49 TidyPointer(TidyPointer<T, DeAllocator> const &);
50 /// Forbidden assigment operator.
51 TidyPointer <T, DeAllocator> & operator = (TidyPointer<T, DeAllocator> const &);
52 /// Deallocate raw pointer. Become a nil pointer.
53 void deletePointer() {
54 if (raw) {
55 DeAllocator(raw);
56 }
57 raw = NULL;
58 }
59 T *raw; ///< pointer to T object or NULL
60 };
61
62 /// DeAllocator for pointers that need free(3) from the std C library
63 template<typename T> void tidyFree(T *p)
64 {
65 xfree(p);
66 }
67
68 #endif // SQUID_BASE_TIDYPOINTER_H
69