天天看點

c++ 實作defer

看到一篇文章,講如何在 Objective-C 的環境下實作 defer,深受啟發。是以在c++下實作了一個版本,效果還不錯。

// 用于定義一個匿名變量名,把行号放到變量名中
#define  __ANONYMOUS1(type, var, line)  type  var##line
#define  _ANONYMOUS0(type, line)  __ANONYMOUS1(type, _anonymous, line)
#define  ANONYMOUS(type)  _ANONYMOUS0(type, __LINE__)

// defer所執行的函數的類型
typedef std::function<void()> __DeferFunc;
void __deferCleanUp(__DeferFunc* func)
{
	(*func)();
}

#define defer \
	__DeferFunc deferCleanUp_##__LINE__ __attribute__((cleanup(__deferCleanUp), unused)) =

void test()
{
	cout << "call the test func!" << endl;
}

int main() {
	if (true)
	{
		// 可以用匿名函數做defer
		defer [](){
			cout<<"will out if block!" << endl;
		};

		// 也可以用普通函數做defer
		defer test;
		cout << "in if block!" << endl;
	}
}

輸出結果:
in if block!
call the test func!
will out if block!