禁用 ScopedGuard 的“未使用的变量”

问题描述 投票:0回答:1

我正在与 Andrei Alexandrescu 和 Petru 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);

我正在使用宏在应对结束时采取一些行动:

#define SCOPE_GUARD ScopedGuard scope_guard = MakeGuard

这样,用户就可以调用

SCOPE_GUARD(&foo, param) ...

这个宏使得很难禁用未使用的警告。

有人可以帮助我更好地理解这一点,并且也许可以在不使用 -Wno-unused-variable 的情况下提供解决方案吗?

c++ compilation gcc-warning unused-variables c++-loki
1个回答
0
投票

你可以尝试旧方法:

 (void)scope_guard;
© www.soinside.com 2019 - 2024. All rights reserved.