C++实现defer
#pragma once
#include <functional>
#define CONNECTION(text1,text2) text1##text2
#define CONNECT(text1,text2) CONNECTION(text1,text2)
class DeferHelper {
public:
DeferHelper(std::function<void ()> &&cb) : cb_(std::move(cb)) {}
~DeferHelper() { if (cb_) cb_(); }
private:
std::function<void ()> cb_;
};
#define defer(code) DeferHelper CONNECT(L,__LINE__) ([&](){code;})
int main() {
defer (std::cout<<"defer 1"<<std::endl);
std::cout<<"pos 1"<<std::endl;
{
defer (std::cout<<"defer 2"<<std::endl);
defer (std::cout<<"defer 3"<<std::endl);
std::cout<<"pos 2"<<std::endl;
}
std::cout<<"pos 3"<<std::endl;
return 0;
}
/* 输出
pos 1
pos 2
defer 3
defer 2
pos 3
defer 1
*/