【发布时间】:2019-04-27 08:44:50
【问题描述】:
鉴于此代码:
template <class Func> class ScopeGuard
{
public:
/** @param func function object to be executed in dtor
*/
explicit ScopeGuard( Func && func ) : m_func( std::move(func) ) {}
~ScopeGuard()
{
if (m_bDismissed)
return;
m_func();
}
/** Dismisses the scope guard, i.e. the function won't
be executed.
*/
void dismiss() { m_bDismissed = true; }
private:
// noncopyable until we have good reasons...
ScopeGuard(const ScopeGuard&) = delete;
ScopeGuard& operator=(const ScopeGuard&) = delete;
Func m_func;
bool m_bDismissed = false;
};
// Get functor for cleanup to use in FlagRestorationGuard
auto GetFlagRestorationGuard(bool& i_flagRef)
{
return [&i_flagRef, resetVal = i_flagRef] { i_flagRef = resetVal; };
}
class FlagRestorationGuard : public ScopeGuard<decltype(GetFlagRestorationGuard(*(new bool)))>
{
public:
FlagRestorationGuard( bool& i_flagRef, bool i_temporaryValue )
: ScopeGuard(GetFlagRestorationGuard(i_flagRef))
{
i_flagRef = i_temporaryValue;
}
};
使用 Apple Clang 为 GetFlagRestorationGuard(*(new bool)) 构建时出现以下错误:
错误:具有副作用的表达式在未评估的上下文中无效 [-Werror,-Wunevaluated-expression]
请注意,此代码可与 MSVC 2017 一起构建并正常工作。
当然,可以全部重写以使用带有operator()() 的结构而不是 lambda 和返回它的函数,但我想知道是否有像这样使用 lambda 的好方法?
Reference 为实际代码:
Reference构建失败:
【问题讨论】: