2016-11-15 07:21:22 +05:30
|
|
|
#pragma once
|
|
|
|
|
|
|
|
#include <cstddef>
|
|
|
|
#include <memory>
|
|
|
|
|
|
|
|
class Usable;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Base class for things that can be used by multiple other things and we want to track the use count.
|
|
|
|
*
|
|
|
|
* @see UseLock
|
|
|
|
*/
|
|
|
|
class Usable
|
|
|
|
{
|
2018-07-15 18:21:05 +05:30
|
|
|
friend class UseLock;
|
2016-11-15 07:21:22 +05:30
|
|
|
public:
|
2018-07-15 18:21:05 +05:30
|
|
|
std::size_t useCount()
|
|
|
|
{
|
|
|
|
return m_useCount;
|
|
|
|
}
|
|
|
|
bool isInUse()
|
|
|
|
{
|
|
|
|
return m_useCount > 0;
|
|
|
|
}
|
2016-11-15 07:21:22 +05:30
|
|
|
protected:
|
2018-07-15 18:21:05 +05:30
|
|
|
virtual void decrementUses()
|
|
|
|
{
|
|
|
|
m_useCount--;
|
|
|
|
}
|
|
|
|
virtual void incrementUses()
|
|
|
|
{
|
|
|
|
m_useCount++;
|
|
|
|
}
|
2016-11-15 07:21:22 +05:30
|
|
|
private:
|
2018-07-15 18:21:05 +05:30
|
|
|
std::size_t m_useCount = 0;
|
2016-11-15 07:21:22 +05:30
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Lock class to use for keeping track of uses of other things derived from Usable
|
|
|
|
*
|
|
|
|
* @see Usable
|
|
|
|
*/
|
|
|
|
class UseLock
|
|
|
|
{
|
|
|
|
public:
|
2018-07-15 18:21:05 +05:30
|
|
|
UseLock(std::shared_ptr<Usable> usable)
|
|
|
|
: m_usable(usable)
|
|
|
|
{
|
|
|
|
// this doesn't use shared pointer use count, because that wouldn't be correct. this count is separate.
|
|
|
|
m_usable->incrementUses();
|
|
|
|
}
|
|
|
|
~UseLock()
|
|
|
|
{
|
|
|
|
m_usable->decrementUses();
|
|
|
|
}
|
2016-11-15 07:21:22 +05:30
|
|
|
private:
|
2018-07-15 18:21:05 +05:30
|
|
|
std::shared_ptr<Usable> m_usable;
|
2016-11-15 07:21:22 +05:30
|
|
|
};
|