This commit is contained in:
Frank Mayer 2024-11-01 22:21:50 +01:00
parent 6a465c5d59
commit d985865048
No known key found for this signature in database
GPG Key ID: 69CC687128401C30
2 changed files with 31 additions and 1 deletions

21
src/defer.h Normal file
View File

@ -0,0 +1,21 @@
#ifndef DEFER_H
#define DEFER_H
#include <functional>
#include <iostream>
class Defer {
public:
Defer(std::function<void()> func) : func_(func) {}
~Defer() { func_(); }
private:
std::function<void()> func_;
};
#define CONCAT_IMPL(a, b) a##b
#define CONCAT(a, b) CONCAT_IMPL(a, b)
#define DEFER(code) Defer CONCAT(defer__, __LINE__)([&]() { code; });
#endif // DEFER_H

View File

@ -1,6 +1,15 @@
#include "defer.h"
#include <iostream>
struct Meep {
std::string foo = "Meep!";
};
int main() {
std::cout << "Hello, World!" << std::endl;
Meep *meep = new Meep();
DEFER(delete meep);
DEFER(std::cout << "Goodbye, " << meep->foo << std::endl);
std::cout << "Hello, " << meep->foo << std::endl;
return 0;
}