c++实现go关键字defer

梦想游戏人
目录:
C/C++

go的defer关键字 ,更像是RAII思想的延续,只不过执行的是用户代码

其中风格3 说明了为什么采用acquire_defer 方式来处理

风格1:

class Defer
{
public:
	~Defer()
	{
		_cb();
	}
	std::function<void(void)> _cb;
};

#define defer(x) std::shared_ptr<Defer>acquire_defer = std::make_shared<Defer>();acquire_defer->_cb=x;

auto x = new int;

void func()
{
	//useage
	defer([=]()
	{
		delete x;
		//do something....
		cout << "111" << endl;
	});

	cout << "2222" << endl;
	//do something...
}

int main(int argc, char* argv[])
{
	func();
	system("pause");
	return 0;
}

风格2:

class Defer
{
public:
	~Defer()
	{
		_cb();
	}
	std::function<void(void)> _cb;
};

#define defer(x) std::shared_ptr<Defer>acquire_defer = std::make_shared<Defer>();acquire_defer->_cb=[=](){x();};

auto x = new int;
void final1()
{
	cout << "111111" << endl;
}

void func()
{
	//useage
	defer(final1);
	cout << "2222" << endl;
	//do something...
}

int main(int argc, char* argv[])
{
	func();
	system("pause");
	return 0;
}

风格3:

class Defer
{
public:
	~Defer()
	{
		_cb();
	}
	std::function<void(void)> _cb;
};

#define defer(x) std::shared_ptr<Defer>acquire_defer = std::make_shared<Defer>();acquire_defer->_cb=x;

auto x = new int;


std::function<void(void)>* _cb;
void func()
{
	//useage
	defer([=]()
	{
		delete x;
		//do something....
		cout << "111" << endl;
	});

	cout << "2222" << endl;
	//do something...

	_cb = new std::function<void(void)>([=]()
	{
		acquire_defer;
		cout << "3333333" << endl;
	});

}

int main(int argc, char* argv[])
{
	func();
//	(*_cb)();
	cout << "44444" << endl;
	delete _cb;
	system("pause");
	return 0;
}

Scroll Up