I have an object, Window, who has a member std::unique_ptr<Texture>
. I use a unique pointer, because Window really owns the texture, and it doesn't make sense to use said Texture after Window has been destroyed.
Window has a method, Texture& Window::getTexture()
. The idea being that sometimes code external to Window will say myWindow.getTexture()
, do something with the texture, and then be done with it.
The risk is that someone holds onto the Texture reference which becomes invalid after Window's destruction. I could instead have window hold an std::shared_ptr<Texture>
and std::weak_ptr<Texture> Window::getTexture()
but shared_ptr feels wrong to me when Window is the sole owner of the texture, and the texture is never meant to outlive the Window.
Is there a particular pattern I should use in a case like this, or is a reference the way to go? In the old days I would of course just return a pointer.
EDIT: I may be overthinking this, here is an example of a normal usage
Texture& tex = myWindow.getTexture();
context.drawHere(tex);
context.drawThere(tex);
context.drawEverywhere(tex);
The calling code would have to do something very abnormal to hold onto the reference, normally you just use it for a few draw calls (which don't hold onto anything). Is this a non-issue, or is there a pattern of some sort I should use to make this explicit beyond documentation?