2017-04-04 59 views
0

林与安德烈Alexandrescu的和彼得鲁杜米特Marginean打scoped guard object禁用“未使用变量”为ScopedGuard

当你与-Wall -Werror编译你会得到“未使用变量”的错误。

ScopeGuard scope_guard = MakeGuard(&foo); 

这只是

const ScopeGuardImplBase& scope_guard = ScopeGuardImpl0<void(*)()>(&foo); 

即时通讯使用宏来得到在一月底的一些动作:下面的代码是从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); 
} 

的问题是使用取应付:

#define SCOPE_GUARD ScopedGuard scope_guard = MakeGuard 

这种方式,用户可以叫

SCOPE_GUARD(&foo, param) ... 

这个宏使其难以禁止未使用的警告。

有人可以帮助我更好地理解这一点,也许提供一个解决方案,而不使用-Wno-unused-variable?

+1

的可能的复制[?如何使用范围后卫时避免警告(http://stackoverflow.com/questions/35587076/how-to-avoid-预警时,使用范围的后卫) –

回答

0

你可以试试老方法:

(void)scope_guard;