I have a vector of unique_ptrs which point to Models, Meshes, etc like this:
std::vector<std::unique_ptr<Model>> mLoadedModels; I choose unique_ptr because it automatically frees the data upon vector destructor, and also because later on if I need to for example reload all the models (due to OpenGL context tear down/created) I can just internally in my resource manager reset() and make it point to a new Model instance and it wouldnt affect the rest of the system.
My question though is, how would you share the contents of the vector with other systems? You cant just pass the unique_ptr around, because that would change the ownership (due to its unique_ptr), and I want sole ownership in the rersource manager.
The solution I came up with is the following, to wrap the access in the following struct:
template<typename T> struct Handle { Handle(std::unique_ptr<T>& resource) : mResource(resource) { } T& operator*() { return mResource.get(); } const T& operator*() const { return mResource.get(); } T* operator->() { return mResource.get(); } const T* operator->() const { return mResource.get(); } private: std::unique_ptr<T>& mResource; }; typedef Handle<Model> ModelPtr; ModelPtr GetModel(const std::string& modelName); // example: ModelPtr monkey = GetModel("Monkey"); monkey->dance(); // reload resources, and then monkey dereferences to the new Model instance It feels abit gimmicky though, surely theres a better, more straightforward solution to this?
shared_ptrif you need shared ownership. You could then hand outweak_ptrs to observers.Handleshould obviously be namedunique_ptr_ptr. Kidding aside, yourHandlewill be invalidated when the vector resizes.Model*?shared_unique_ptrto deal with lifetime issues (I kid).shared_unique_ptr*to cover all my bases.