lib: moved vSmartPtr<> from opensync plugin code to main library
[barry.git] / src / vsmartptr.h
blobb59875443b4b1feb861a485541e89077760530be
1 ///
2 /// \file vsmartptr
3 /// Variable 'free' smart pointer
4 ///
6 /*
7 Copyright (C) 2006-2009, Net Direct Inc. (http://www.netdirect.ca/)
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 2 of the License, or
12 (at your option) any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
18 See the GNU General Public License in the COPYING file at the
19 root directory of this project for more details.
22 #ifndef __BARRY_VSMARTPTR_H__
23 #define __BARRY_VSMARTPTR_H__
25 namespace Barry {
28 // vSmartPtr
30 /// A special smart pointer for variables that have their own
31 /// special 'free' functions. Behaves like std::auto_ptr<>
32 /// in that only one object at a time owns the pointer,
33 /// and destruction frees it by calling the given FreeFunc.
34 ///
35 template <class T, class FT, void (*FreeFunc)(FT *pt)>
36 class vSmartPtr
38 mutable T *m_pt;
40 public:
41 vSmartPtr() : m_pt(0) {}
42 vSmartPtr(T *pt) : m_pt(pt) {}
43 vSmartPtr(const vSmartPtr &sp) : m_pt(sp.m_pt)
45 sp.m_pt = 0;
47 ~vSmartPtr()
49 if( m_pt )
50 FreeFunc(m_pt);
53 vSmartPtr& operator=(T *pt)
55 Extract();
56 m_pt = pt;
57 return *this;
60 vSmartPtr& operator=(const vSmartPtr &sp)
62 Extract();
63 m_pt = sp.Extract();
64 return *this;
67 T* Extract()
69 T *rp = m_pt;
70 m_pt = 0;
71 return rp;
74 T* Get()
76 return m_pt;
82 Example usage:
84 typedef vSmartPtr<b_VFormatAttribute, b_VFormatAttribute, &b_vformat_attribute_free> vAttrPtr;
85 typedef vSmartPtr<b_VFormatParam, b_VFormatParam, &b_vformat_attribute_param_free> vParamPtr;
86 typedef vSmartPtr<char, void, &g_free> gStringPtr;
90 } // namespace Barry
92 #endif