Peretz Levinov
Peretz Levinov

Reputation: 1

Disable "Unused variable" for ScopedGuard

Im playing with Andrei Alexandrescu and Petru Marginean scoped guard object

When you compile it with -Wall -Werror you get "unused variable" error. The following code is taken from 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);
}

the problem is with the usage:

ScopeGuard scope_guard = MakeGuard(&foo);

which is just

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

Im using Macro to get some action at the end of a cope:

#define SCOPE_GUARD ScopedGuard scope_guard = MakeGuard

this way, the user can just call

SCOPE_GUARD(&foo, param) ...

this macro making it hard disabling the unused warning.

Can someone help me understand this better and maybe offer a solution to this without using -Wno-unused-variable?

Upvotes: 0

Views: 312

Answers (1)

Alex
Alex

Reputation: 10126

You can try the old method:

 (void)scope_guard;

Upvotes: 0

Related Questions