Created
February 7, 2022 14:30
-
-
Save linkdd/1b23f3979f283576c32294b1046852e5 to your computer and use it in GitHub Desktop.
Golang's defer feature for your C++ functions.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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); | |
} | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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