Skip to content

BlackMATov/defer.hpp

Repository files navigation

defer.hpp

Go's defer implementation in C++17

linux darwin windows language license

Requirements

Installation

defer.hpp is a header-only library. All you need to do is copy the headers files from headers directory into your project and include them:

#include "defer.hpp/defer.hpp"

Also, you can add the root repository directory to your cmake project:

add_subdirectory(external/defer.hpp)
target_link_libraries(your_project_target PUBLIC defer.hpp::defer.hpp)

Examples

Basic Defer

if ( FILE *file = std::fopen("output.txt", "a") ) {
    // defer will close the file after scope or on exception
    DEFER_HPP([file]{ std::fclose(file); });

    const char buffer[] = "hello world\n";
    if ( 12 != std::fwrite(buffer, sizeof(buffer[0]), std::strlen(buffer), file) ) {
        throw std::runtime_error("some exception");
    }
}

Error Defer

if ( FILE *file = std::fopen("output.txt", "a") ) {
    // defer will close the file after scope or on exception
    DEFER_HPP([file]{ std::fclose(file); });

    // error defer will be called on exception
    ERROR_DEFER_HPP([]{
        std::cerr << "there is something wrong" << std::endl;
    });

    const char buffer[] = "hello world\n";
    if ( 12 != std::fwrite(buffer, sizeof(buffer[0]), std::strlen(buffer), file) ) {
        throw std::runtime_error("some exception");
    }
}

Return Defer

if ( FILE *file = std::fopen("output.txt", "a") ) {
    // defer will close the file after scope or on exception
    DEFER_HPP([file]{ std::fclose(file); });

    // return defer will be called on successful scope exit
    RETURN_DEFER_HPP([]{
        std::cout << "all is ok!" << std::endl;
    });

    const char buffer[] = "hello world\n";
    if ( 12 != std::fwrite(buffer, sizeof(buffer[0]), std::strlen(buffer), file) ) {
        throw std::runtime_error("some exception");
    }
}