// Copyright (c) Softanics

#pragma once

#include <assert.h>

/// Base class of classes which lifetime is based on reference count
class CObjectWithCounter
{
private:
    volatile LONG m_nRefCount;

protected:
    CObjectWithCounter() : 
        m_nRefCount(0)
    {
    }

    virtual ~CObjectWithCounter()
    {
        assert(0 == m_nRefCount);
    }

    virtual LONG GetRefCount()
    {
        return m_nRefCount;
    }

public:
    virtual ULONG __stdcall AddRef()
    {
        return (ULONG)InterlockedIncrement(&m_nRefCount);
    }

    virtual ULONG __stdcall Release()
    {
        LONG lRes = InterlockedDecrement(&m_nRefCount);

        if (0 == m_nRefCount)
            delete this;

        return (ULONG)lRes;
    }
};
