I have implemented a resource handle and resource cache class. The handle stores an integer id. The cache stores a vector of objects e.g., Textures. The handle id acts as an index into the cache asset vector.
I then have a third class which provides methods to get the object(Texture) associated with a given handle. The class also stores a map of filename, handle for previously loaded objects.
I am trying to add reference counting to the system. At the moment I store a std::size_t* ref_count
in Resource_handle
and have the following constructor/destructor/assignment operators:
Resource_handle() : id(0), verifier(0), ref_count(new std::size_t(1)) {}
Resource_handle(const Resource_handle<T>& handle)
: id(handle.id), verifier(handle.verifier), ref_count(handle.ref_count) { ++*ref_count; }
template<typename T>
Resource_handle<T>& Resource_handle<T>::operator=(const Resource_handle<T>& rhs)
{
++*rhs.ref_count;
if (--*ref_count == 0) {
delete ref_count;
// reset handle
}
id = rhs.id;
verifier = rhs.verifier;
return *this;
}
template<typename T>
Resource_handle<T>::~Resource_handle() // reference handling 515 C++ Primer
{
if (--*ref_count == 0) {
delete ref_count;
// unload resource in handle
// reset handle?
reset();
}
}
The above code is not complete but I have two problems I'm aware of so far.
The objects in the
Resource_cache
vector are not allocated on the heap andResource_handle
has no pointer to them to delete them.The reference count
ref_count
is actually counting copies of a particular handle rather than of objects in the cache vector.
How can I resolve these two issues? I'm wondering if the reference handling should be done in the cache class instead? However the cache would have no knowledge of how many handles refer to a particular object in its object vector.
Many thanks.
Edit: I did consider std::shared_ptr<T>
however research lead me to using handles for the ability to reload resources, easier serialisation and the more lightweight approach.