summaryrefslogtreecommitdiffstats
path: root/api/logic/Usable.h
blob: 1168be4d210b6bf79798af554b31f3fa8149b789 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#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
{
	friend class UseLock;
public:
	std::size_t useCount()
	{
		return m_useCount;
	}
	bool isInUse()
	{
		return m_useCount > 0;
	}
protected:
	virtual void decrementUses()
	{
		m_useCount--;
	}
	virtual void incrementUses()
	{
		m_useCount++;
	}
private:
	std::size_t m_useCount = 0;
};

/**
 * Lock class to use for keeping track of uses of other things derived from Usable
 *
 * @see Usable
 */
class UseLock
{
public:
	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();
	}
private:
	std::shared_ptr<Usable> m_usable;
};