Skip to content

Instantly share code, notes, and snippets.

@ChunMinChang
Created February 7, 2019 23:13
Show Gist options
  • Save ChunMinChang/879359c4362620691f0b19423ac18239 to your computer and use it in GitHub Desktop.
Save ChunMinChang/879359c4362620691f0b19423ac18239 to your computer and use it in GitHub Desktop.
Finally: A function call that runs at the end of a scope to tear things down.
#ifndef FINALLY_H
#define FINALLY_H
#include <utility>
template<class Lambda>
class Finally {
public:
Finally(Lambda &&func): func_(std::forward<Lambda>(func)) {};
~Finally() { func_(); };
private:
Lambda func_;
};
template<class Lambda>
Finally<Lambda> make_finally(Lambda &&func) {
return { std::forward<Lambda>(func) };
}
#endif // FINALLY_H
// Compile by `$ g++ main.cpp`
#include "finally.h"
#include <cstdlib>
#include <iostream>
using std::cout;
using std::endl;
int main() {
int* data = (int*) calloc(1, sizeof(int));
*data = 3141592;
auto finally = make_finally([data] {
cout << "Run the following code before going out this scope." << endl;
cout << "Free data " << *data << endl;
free(data);
});
cout << "Do something here first..." << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment