#pragma once

#include <functional>

struct scope_guard {
	typedef std::function<void()> Fn;
	Fn action;
	bool active;

    scope_guard(Fn action) : action(action), active(true) {}

	void dismiss() {
		active = false;
	}
    ~scope_guard () {
		if(active) action();
    }
};

test:

 

#include <windows.h>

#include <iostream>
using namespace std;

#include "scope_guard.h"

void test() {
	void* memory = malloc(100);
	scope_guard g([&]() { 
		free(memory);
		cout << "memory freed" << endl;
	});

	bool error_occur = true;
	if(error_occur) return;

	g.dismiss();
}
int main() {
	test();
}


 

 

相关文章:

  • 2021-10-18
  • 2021-06-14
  • 2022-12-23
  • 2021-10-04
  • 2021-11-21
  • 2021-10-10
  • 2021-11-12
  • 2021-11-29
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-07-28
  • 2021-12-29
  • 2021-06-02
  • 2021-05-18
  • 2021-09-01
相关资源
相似解决方案