Last active
November 14, 2016 23:52
-
-
Save peterix/4c6f1543abd6c7d6efd668a7da928be0 to your computer and use it in GitHub Desktop.
Use tracking thingy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} | |
private: | |
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; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment