Skip to content

Instantly share code, notes, and snippets.

@progschj
Created April 8, 2013 00:14
Show Gist options
  • Save progschj/5333237 to your computer and use it in GitHub Desktop.
Save progschj/5333237 to your computer and use it in GitHub Desktop.
Helper class to use "RAII" with nonpointer objects
#ifndef ON_DESTROY_H
#define ON_DESTROY_H
#include <functional>
#include <utility>
class on_destroy {
public:
on_destroy() { }
template<class F, class... Args>
on_destroy(F&& f, Args&&... args)
: function(std::bind(std::forward<F>(f), std::forward<Args>(args)...))
{
}
on_destroy& operator=(on_destroy &&that)
{
function = std::move(that.function);
return *this;
}
~on_destroy()
{
if(function)
function();
}
private:
std::function<void()> function;
};
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment