Skip to content

Instantly share code, notes, and snippets.

@nmandery
Created March 7, 2012 20:32
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 nmandery/1995912 to your computer and use it in GitHub Desktop.
Save nmandery/1995912 to your computer and use it in GitHub Desktop.
Go-like defer statement (C++11)
/**
* Go-like defer statement (C++11)
*
* g++ --std=c++0x -o def def.cc
*
* also see http://blog.korfuri.fr/post/go-defer-in-cpp/
*/
#include <functional>
#include <iostream>
#define DEFER_UQ(A, UQID) defer defr_ ##UQID ([]{ A;});
#define DEFER_CALL(A, UQ) DEFER_UQ(A, UQ)
#ifdef __COUNTER__
#define DEFER(A) DEFER_CALL(A, __COUNTER__)
#else
#define DEFER(A) DEFER_CALL(A, __LINE__)
#endif
class defer {
std::function<void()> t;
public:
defer(std::function<void()> &&t) : t(t) {}
~defer() { t(); }
};
int main() {
defer d([]{ std::cout << " world!!" << std::endl; });
DEFER(std::cout << "... and again" << std::endl)
DEFER(std::cout << "... plus once more." << std::endl)
std::cout << "Hello";
}
@Nameguy
Copy link

Nameguy commented May 3, 2016

Awful for efficiency - std::function<> does type erasure via heap allocations. Salty syntax.

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