Skip to content

Instantly share code, notes, and snippets.

@AndyDentFree
Last active August 29, 2015 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AndyDentFree/e6e46dd1abd9b2c2a885 to your computer and use it in GitHub Desktop.
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
// 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;
}
@AndyDentFree
Copy link
Author

Console output will be:
Hello, World!
Inside nestedFunc!
Invoked stacked on exit!
Invoked on exit!
Goodbye, World!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment