Defer

Defer

Sergey Abbakumov

Sometimes when exiting a function one wants to run some code, which, for example, will close resources, do some sort of logging, etc. In C++, it is customary to do various Scoped objects that are created on the stack and when they exit the scope they do something in the destructor (RAII). But there are situations when the creation of classes and objects is inappropriate. The Defer, borrowed from Go, comes for help (https://github.com/sabbakumov/rst/tree/master/rst/Defer):


void Foo() {}
void Bar() {
  RST_DEFER(&Foo);
}


Since the template is hidden inside, you can transfer any objects that are callable:


void Bar() {
  std::FILE* f = std::fopen("file.txt", "r");
  RST_DEFER([f]() { std::fclose(f); });
}

void Baz(int) {}
void Func() {
  RST_DEFER(std::bind(&Baz, 10));
}


Telegram channel: https://t.me/sea_plus_plus

Report Page