Created
February 7, 2019 23:13
-
-
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.
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
#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 |
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
// 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