Last active
August 29, 2015 14:22
-
-
Save AndyDentFree/e6e46dd1abd9b2c2a885 to your computer and use it in GitHub Desktop.
Shows how modern C++ can use RAII helper objects to provide the "defer" feature just introduced in Swift 2.0
This file contains hidden or 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
// shows how C++11 can implement the "defer" introduced in Swift 2.0 | |
#include <iostream> | |
using simpleClosure = std::function<void()>; // new typedef syntax used for closure | |
// class only needs to be declared once then used all over to wrap closures | |
// see http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization | |
class deferRAII { | |
public: | |
deferRAII(simpleClosure cl) : runOnDestruction(cl) {} | |
~deferRAII() { runOnDestruction(); } | |
private: | |
simpleClosure runOnDestruction; | |
}; | |
void nestedFunc() | |
{ | |
deferRAII x( ^(){std::cout << "Invoked on exit!\n";} ); | |
std::cout << "Inside nestedFunc!\n"; | |
deferRAII x2( ^(){std::cout << "Invoked stacked on exit!\n";} ); | |
} | |
int main(int argc, const char * argv[]) { | |
std::cout << "Hello, World!\n"; | |
nestedFunc(); | |
std::cout << "Goodbye, World!\n"; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Console output will be:
Hello, World!
Inside nestedFunc!
Invoked stacked on exit!
Invoked on exit!
Goodbye, World!