Skip to content

Instantly share code, notes, and snippets.

@linkdd
Created February 7, 2022 14:30
Show Gist options
  • Save linkdd/1b23f3979f283576c32294b1046852e5 to your computer and use it in GitHub Desktop.
Save linkdd/1b23f3979f283576c32294b1046852e5 to your computer and use it in GitHub Desktop.
Golang's defer feature for your C++ functions.
#pragma once
#include <functional>
#include <vector>
#include <algorithm>
class defer_frame {
public:
using function = std::function<void(void)>;
private:
std::vector<function> m_funcs;
public:
~defer_frame() {
std::for_each(m_funcs.rbegin(), m_funcs.rend(), [](auto &f) {
f();
});
}
void defer(function fn) {
m_funcs.push_back(fn);
}
};
#include <iostream>
#include "defer-frame.hpp"
int main() {
defer_frame _;
auto val = create_resource();
if (val == nullptr) {
std::cerr << "ERROR" << std::endl;
return 1;
}
_.defer([&]() { destroy_resource(val); });
auto val2 = create_resource();
if (val2 == nullptr) {
std::cerr << "ERROR" << std::endl;
return 1;
}
_.defer([&]() { destroy_resource(val2); });
do_something(val, val2);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment