Unique pointers look interesting as well; you can still control life of the object quite easy and they are faster and smaller in memory (still 8 bytes). But forward declared unique pointers have some issues.
So, integers can be small in memory (2-4 bytes are sufficient); but there are a lot of issues with integer as handles, but thanks to Modern C++ you can improve a lot of them.
A template class wrapping the integer could hide it and avoid assignations between different types of handles. But you can do more; it can control the ownership and leaks as well. The template class will look like:
template <typename DATA, typename TYPE> class Handle { Handle() { m_index = kInvalid; } ~Handle() { assert(m_index == kInvalid); } Handle(const Handle& a) = delete; Handle& operator=(const Handle& a) = delete; private: TYPE m_index; static TYPE kInvalid = static_cast<TYPE>(-1); };
Similar to unique pointers; you can only move them, copy will fail to compile. During the destruction the index MUST be invalid, that happens only if you have destroyed it. So if a Handle calls the destructor and still has a valid handle; you found a leak.
But sometimes you need to copy handles, so we can introduce a WeakHandle template class; a WeakHandle can be copied but it can not be used for destroying the handle (only a Handle can).
Conclusion:
You can have the best of shared pointers or unique pointers but the size and simplicity of an integer with a minimal implementation of a wrapper class.Extra:
What happens when a Handle is deleted and still there is a WeakHandle alive?It can produce issues as you can still use a deleted handle in the system, but it is quite easy to track. WeakHandles can increase a ref count for the index (maintained in the library) during construction and decrease it during destruction, that will allow us to check if all the WeakHandles have been deleted at the moment of the Handle destruction (this code can be activated just for tracking these issues).
Code: https://github.com/JlSanchezB/Cute/blob/master/engine/core/handle_pool.h
No comments:
Post a Comment