#include <iostream>
using namespace std;
#include <functional>
template <class F>
class ScopeExitFunction
{
public:
ScopeExitFunction(F& func) throw() :
m_func(func)
{
}
ScopeExitFunction(F&& func) throw() :
m_func(std::move<F>(func))
{
}
ScopeExitFunction(ScopeExitFunction&& other) throw() :
m_func(std::move(other.m_func))
{
// other.m_func = []{};
}
~ScopeExitFunction() throw()
{
m_func();
}
private:
F m_func;
};
int main() {
{
std::function<void()> lambda = [] { cout << "called" << endl; };
ScopeExitFunction<decltype(lambda)> f(lambda);
ScopeExitFunction<decltype(lambda)> f2(std::move(f));
}
return 0;
}
如果不取消注释此行// other.m_func = []{};
,程序会产生以下输出:
执行程序.... $demo 调用终止,在抛出 'std::bad_function_call' 的实例后调用 what(): bad_function_call
std::function 移动时不重置其内部功能是否正常?