Giter Site home page Giter Site logo

defer's Introduction

Defer a function/lambda until the end of the scope

Inspired by the defer keyword in Go, this simple defer function in C++ provides similar functionality. In contrast to Go, the deferred function is called at the end of the current scope. In Go the deferred function is only called at the end of the current function scope.

The main use for this C++ defer function is to simplify resource cleanup safety in simple situations where the definition of a complete new RAII class would be overkill.

Example:

void f(const std::string &filename) {
  auto fp = std::fopen(filename.c_str(), "r");
  if (!fp) {
    std::perror("File opening failed");
    return;
  }
  DEFER({ std::fclose(fp); });
  // do stuff that can throw or return early. The file stream will be closed in
  // any case
}

There are two possible interfaces to using the defer function in defer.h:

  1. Either use the preprocessor macro (yuck) as shown above (this avoids some boilerplate code/syntax). The macro constructs a lambda and expects the lambda body as its argument.
  2. Or declare a local object, which you capture from the return value of ext::defer. Note that ext::defer works with any callable, so you could also use a std::function or standard function pointer here.
const auto &defer_fclose = ext::defer([&fp] { std::fclose(fp); });

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.