【发布时间】:2013-11-15 10:02:50
【问题描述】:
#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 调用 terminate 之后调用 抛出 'std::bad_function_call' what() 的实例: bad_function_call
std::function 移动时不重置其内部函数是否正常?
【问题讨论】:
-
std::forward<F>(func),在来自F&&的构造函数中只是一种尴尬的说法std::move(func)。 -
msvc2013 下有一个错误,这就是我使用 std::forward 的原因
-
msvc2010 的勘误错误