AutoUnlocker.h

// AutoUnlocker.h
//
// Author David Barrett-Lennard  
// (C)opyright Cedanet Pty Ltd 2006

namespace ceda
{

template<typename T>
class AutoUnlocker
{
private:
    // Not cloneable
    AutoUnlocker(const AutoUnlocker& other); 
    AutoUnlocker& operator=(const AutoUnlocker& other);

public:
    AutoUnlocker(T* ptr = nullptr) : m_ptr(ptr) {}
    ~AutoUnlocker() { if (m_ptr) m_ptr->Unlock(); }

    T& operator*() const { return *m_ptr; }
    T* operator->() const { return m_ptr; }

    AutoUnlocker& operator=(T* ptr)
    {
        if (m_ptr) m_ptr->Unlock();
        m_ptr = ptr;
        return *this;
    }

    void Set(T* ptr)
    { 
        if (m_ptr) m_ptr->Unlock();
        m_ptr = ptr;
    }
    T* Get() const { return m_ptr; }

    explicit operator bool() const { return m_ptr != nullptr; }

private:
    T* m_ptr;
};

}