2020-06-05 00:05:14 +07:00
2020-06-05 00:05:14 +07:00
2020-06-04 23:15:00 +07:00
2020-06-05 00:05:14 +07:00
2020-06-04 23:15:00 +07:00
2020-06-04 23:15:00 +07:00
2020-06-04 23:15:00 +07:00
2020-06-04 23:15:00 +07:00
2020-06-04 23:15:00 +07:00
2020-06-04 23:15:00 +07:00
2020-06-05 00:05:14 +07:00

defer.hpp

travis appveyor codecov language license paypal

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 defer.hpp)

Examples

Basic Defer

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

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

Error Defer

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

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

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

Return Defer

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

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

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

License (MIT)

Description
Languages
C++ 64.3%
CMake 35.7%