Scenario is, I’m building a game with a TextureManager class that is responsible for loading and managing textures. Game objects implementing IVisibleGameObject will need a pointer/reference to a texture from the TextureManager.
Texture manager is implemented with a std::map<std::string, boost::shared_ptr<Texture> > to hold its objects internally.
I’m not certain how I should actually expose the textures, and thought of a few possibilities, each with their own downsides:
1) const Texture& GetTex(std::string textureKey)
I feel would be ideal, but I’d like to indicate that a texture was not found in the map by returning NULL. (Second guessing myself…IS this appropriate?)
2) shared_ptr<const Texture> GetTex(std::string textureKey)
Here I could return a null shared_ptr, but I’m uncomfortable with the implication it’s a shared object now. The TextureManager is the object’s owner, it’s the manager after all. However, considering the fact an IVisibleGameObject holds a reference/pointer to the returned Texture and depends on its existence to function correctly, isn’t it also an owner of the object, and maybe shared ownership is appropriate?
3) const Texture* GetTex(stD::string textureKey)
Obviously, this is the wrong answer.
Would love for someone to clear this up for me, perhaps there is something I haven’t considered.
I would stick with the standard library idiom and simply expose
findandend. Then you can be perfectly efficient:The standard library already has a perfectly serviceable, generic idiom for handling collections and signaling presence or absence of elements, as well as combining insert-new-or-return-existing semantics. Why reinvent the wheel…