utils: add auto_raii helper function

this helper permits to register a resource and cleanup function to keep
exception safety with C like resource. For exemple, to be sure that a
FILE* will be closed, you can use:

auto file = auto_raii(fopen("filename"), fclose);

file will auto cast to FILE* when needed, and will call fclose when
going out of scope.
This commit is contained in:
Maxime Coste 2011-09-14 15:36:35 +00:00
parent eecc5a184e
commit 4b38cd3cd0

View File

@ -39,6 +39,35 @@ bool operator== (const std::unique_ptr<T>& lhs, T* rhs)
return lhs.get() == rhs; return lhs.get() == rhs;
} }
template<typename T, typename F>
class AutoRaii
{
public:
AutoRaii(T* resource, F cleanup)
: m_resource(resource), m_cleanup(cleanup) {}
AutoRaii(AutoRaii&& other) : m_resource(other.m_resource),
m_cleanup(other.m_cleanup)
{ other.m_resource = nullptr; }
AutoRaii(const AutoRaii&) = delete;
AutoRaii& operator=(const AutoRaii&) = delete;
~AutoRaii() { if (m_resource) m_cleanup(m_resource); }
operator T*() { return m_resource; }
private:
T* m_resource;
F m_cleanup;
};
template<typename T, typename F>
AutoRaii<T, F> auto_raii(T* resource, F cleanup)
{
return AutoRaii<T, F>(resource, cleanup);
}
} }
#endif // utils_hh_INCLUDED #endif // utils_hh_INCLUDED