1 #ifndef INC_AUTO_HANDLE_H
2 #define INC_AUTO_HANDLE_H
4 // Like auto_ptr, but for arbitrary "handle" types.
6 // - handle_type: the type of the raw handle to be wrapped
7 // - closer_type: a function object type whose operator() takes a raw handle
8 // and closes it (or does nothing if it is a null handle)
9 // - factory_type: a function object type whose operator() returns a null
12 template<typename handle_type, typename closer_type, typename factory_type>
13 class auto_handle_ref;
15 template<typename handle_type, typename closer_type, typename factory_type>
17 // Use inheritance so we can benefit from the empty base optimisation
18 : private closer_type, private factory_type
20 typedef auto_handle_ref<handle_type, closer_type, factory_type> ref_type;
23 : handle_(factory_type::operator()())
25 explicit auto_handle(handle_type handle)
28 auto_handle(ref_type other)
29 : handle_(other.release())
31 auto_handle & operator=(auto_handle & other)
33 reset(other.release());
39 handle_type get() const
45 handle_type handle(handle_);
46 handle_ = factory_type::operator()();
51 closer_type::operator()(handle_);
52 handle_ = factory_type::operator()();
54 void reset(handle_type handle)
56 closer_type::operator()(handle_);
61 return ref_type(*this);
67 template<typename handle_type, typename closer_type, typename factory_type>
70 typedef auto_handle<handle_type, closer_type, factory_type> target_type;
72 explicit auto_handle_ref(target_type & target)
77 return target_.release();
80 target_type & target_;
83 #endif // !INC_AUTO_HANDLE_H