Created
March 25, 2019 08:40
-
-
Save ipid/e0cdd6be772cb3b961836f7672ab006b to your computer and use it in GitHub Desktop.
Simple Scope-guard(defer) implementation under C++17.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pragma once | |
#ifndef DEFER_HPP_DEFINED | |
#define DEFER_HPP_DEFINED | |
/* | |
defer.hpp v20190325 | |
Simple Scope-guard(defer) implementation under C++17. | |
Released under MIT License. | |
Support: C++17 | |
Usage: | |
1. Include defer.hpp | |
2. Pass any callable object into Defer's constructor. | |
Example 1: | |
Defer defer = [] () { | |
std::cout << "Defer" << std::endl; | |
}; | |
Example 2: | |
void func() { | |
std::cout << "Defer" << std::endl; | |
} | |
int main() { | |
std::function<void()> f = func; | |
Defer defer = f; | |
} | |
*/ | |
template <class T> | |
class Defer { | |
public: | |
Defer(T& fn) : fn(fn) {} | |
Defer(T&& fn) : fn(std::move(fn)) {} | |
// The object is unmovable once it's constructed. | |
Defer() noexcept = delete; | |
Defer(const Defer &) noexcept = delete; | |
Defer(const Defer &&) noexcept = delete; | |
Defer& operator=(const Defer &) noexcept = delete; | |
Defer& operator=(const Defer &&) noexcept = delete; | |
void* operator new (std::size_t) noexcept = delete; | |
void* operator new[](std::size_t) noexcept = delete; | |
~Defer() { | |
this->fn(); | |
} | |
private: | |
T fn; | |
}; | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment