Skip to content

Instantly share code, notes, and snippets.

@r-lyeh-archived
Created October 2, 2015 19:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save r-lyeh-archived/3b35e5f7a47b96f991cd to your computer and use it in GitHub Desktop.
Save r-lyeh-archived/3b35e5f7a47b96f991cd to your computer and use it in GitHub Desktop.
defer c++11
// src: http://www.gingerbill.org/article/defer-in-cpp.html
// This code requires C++11 features such as move semantics
#pragma once
#include <functional>
namespace Impl
{
template <typename Func>
struct Defer
{
Func func;
Defer(Func&& func)
: func(std::forward<Func>(func))
{
}
~Defer()
{
func();
}
};
template <typename Func>
Defer<Func> deferFunc(Func&& func)
{
return Defer<Func>(std::forward<Func>(func));
}
#define DEFER_1(x, y) x##y
#define DEFER_2(x, y) DEFER_1(x, y)
#define DEFER_3(x) DEFER_2(x, __COUNTER__)
#define defer(code) auto DEFER_3(_defer_) = Impl::deferFunc([&](){code;});
} // namespace Impl
/*
// example:
void someFunc()
{
FILE* file = fopen("filename.ext", "rb");
if (file == nullptr)
return;
defer(fclose(file));
u8* buffer = (u8*)allocate(64 * sizeof(u8));
if (buffer == nullptr)
return; // fclose is called automatically
defer(deallocate(buffer));
defer({
printf("You can even defer ");
printf("an entire block too!");
});
// Do whatever...
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment