Skip to content

Instantly share code, notes, and snippets.

@navrocky
Last active June 10, 2025 09:06
Show Gist options
  • Save navrocky/9bb2f9900163f5da7f7989dd438183ab to your computer and use it in GitHub Desktop.
Save navrocky/9bb2f9900163f5da7f7989dd438183ab to your computer and use it in GitHub Desktop.
C++ finalizer like Go defer
#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__) = [&]
@navrocky
Copy link
Author

navrocky commented Feb 7, 2023

Usage example:

cout << "Opened" << endl;
finalize { cout << "Closed" << endl; };
throw "Bang!";

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment