Skip to content

Instantly share code, notes, and snippets.

@krabicezpapundeklu
Last active January 3, 2019 19:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save krabicezpapundeklu/ac6c5fae9d1429917b7ca6fc42bc8047 to your computer and use it in GitHub Desktop.
Save krabicezpapundeklu/ac6c5fae9d1429917b7ca6fc42bc8047 to your computer and use it in GitHub Desktop.
DEFER macro for C++
#pragma once
template
<
typename T
>
class defer
{
public:
defer(T action)
: action_{action}
{
}
~defer()
{
action_();
}
private:
T action_;
};
template
<
typename T
>
defer<T> make_defer(T action)
{
return defer<T>(action);
}
#define DEFER(...) \
DEFER_IMPL_1(__LINE__, __VA_ARGS__)
#define DEFER_IMPL_1(LINE, ...) \
DEFER_IMPL_2(LINE, __VA_ARGS__)
#define DEFER_IMPL_2(LINE, ...) \
const auto defer_##LINE = make_defer([&](){__VA_ARGS__;})
@krabicezpapundeklu
Copy link
Author

Usage:

if(SDL_Init(SDL_INIT_VIDEO))
{
    return EXIT_FAILURE;
}

DEFER(SDL_Quit());

...

std::array<GLuint, 3> buffers;
glGenBuffers(buffers.size(), buffers.data());
DEFER(glDeleteBuffers(buffers.size(), buffers.data()));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment