#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();
}

  



转载于:https://www.cnblogs.com/aj3423/archive/2013/05/28/3150497.html

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐