Last active
June 10, 2025 09:06
-
-
Save navrocky/9bb2f9900163f5da7f7989dd438183ab to your computer and use it in GitHub Desktop.
C++ finalizer like Go defer
This file contains hidden or 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 | |
#include <utility> | |
/** | |
* Execute block on out of scope. | |
* | |
* Example: | |
* | |
* auto file = open("file.txt"); | |
* finalize { close(file); }; | |
* | |
*/ | |
template <typename T> | |
class Finalizator { | |
public: | |
Finalizator(T&& block) | |
: block(std::move(block)) | |
{ | |
} | |
Finalizator(const Finalizator&) = delete; | |
~Finalizator() { block(); } | |
private: | |
T block; | |
}; | |
#define CONCAT_IMPL__(s1, s2) s1##s2 | |
#define CONCAT__(s1, s2) CONCAT_IMPL__(s1, s2) | |
#define finalize Finalizator CONCAT__(finalize_block_, __COUNTER__) = [&] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage example: