我在和安德烈· Alexandria 雷斯库和彼得鲁·马吉尼安一起玩
当你用-Wall -Werror编译它时,你会得到“未使用的变量”错误。下面的代码取自LOKI
class ScopeGuardImplBase
{
ScopeGuardImplBase& operator =(const ScopeGuardImplBase&);
protected:
~ScopeGuardImplBase()
{}
ScopeGuardImplBase(const ScopeGuardImplBase& other) throw()
: dismissed_(other.dismissed_)
{
other.Dismiss();
}
template <typename J>
static void SafeExecute(J& j) throw()
{
if (!j.dismissed_)
try
{
j.Execute();
}
catch(...)
{}
}
mutable bool dismissed_;
public:
ScopeGuardImplBase() throw() : dismissed_(false)
{}
void Dismiss() const throw()
{
dismissed_ = true;
}
};
////////////////////////////////////////////////////////////////
///
/// \typedef typedef const ScopeGuardImplBase& ScopeGuard
/// \ingroup ExceptionGroup
///
/// See Andrei's and Petru Marginean's CUJ article
/// http://www.cuj.com/documents/s=8000/cujcexp1812alexandr/alexandr.htm
///
/// Changes to the original code by Joshua Lehrer:
/// http://www.lehrerfamily.com/scopeguard.html
////////////////////////////////////////////////////////////////
typedef const ScopeGuardImplBase& ScopeGuard;
template <typename F>
class ScopeGuardImpl0 : public ScopeGuardImplBase
{
public:
static ScopeGuardImpl0<F> MakeGuard(F fun)
{
return ScopeGuardImpl0<F>(fun);
}
~ScopeGuardImpl0() throw()
{
SafeExecute(*this);
}
void Execute()
{
fun_();
}
protected:
ScopeGuardImpl0(F fun) : fun_(fun)
{}
F fun_;
};
template <typename F>
inline ScopeGuardImpl0<F> MakeGuard(F fun)
{
return ScopeGuardImpl0<F>::MakeGuard(fun);
}
字符串
问题在于使用:
ScopeGuard scope_guard = MakeGuard(&foo);
型
这只是
const ScopeGuardImplBase& scope_guard = ScopeGuardImpl0<void(*)()>(&foo);
型
我使用宏得到一些科普结束时的一个范围:
#define SCOPE_GUARD ScopedGuard scope_guard = MakeGuard
型
这样用户就可以直接调用
SCOPE_GUARD(&foo, param) ...
型
这个宏使得禁用未使用的警告很困难。
有人能帮助我更好地理解这一点,也许提供一个解决方案,而不使用-Wno-unused-variable?
1条答案
按热度按时间vuktfyat1#
你可以试试老方法:
字符串