[英]Disable “Unused variable” for ScopedGuard
林與安德烈Alexandrescu的和彼得魯杜米特Marginean玩范圍的警衛對象
使用-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);
我正在使用Macro在應對結束時采取一些措施:
#define SCOPE_GUARD ScopedGuard scope_guard = MakeGuard
這樣,用戶可以打電話
SCOPE_GUARD(&foo, param) ...
此宏很難禁用未使用的警告。
有人可以幫助我更好地理解這一點,也許可以在不使用-Wno-unused-variable的情況下提供解決方案嗎?
您可以嘗試使用舊方法:
(void)scope_guard;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.