Reputation: 54183
I'm creating a gui api for games. I have for example a font for each widget in the form of a Font* . Right now I have it so that I do not ever manage the memory of these (for obvious reasons) because I think the user can use smart pointers if they want this memory managed. The con to this is that it is not very idiot proof. If a user set the font like this:
obj.setFont(new Font(""));
This would immediately cause a memory leak because no one ever frees it. The only way would be to delete getFont();
Would it be instead better for me to manage these?
Thanks
Upvotes: 2
Views: 102
Reputation: 76835
It's your decision if your library should take ownership of the resource, but whatever you choose, make it clear through the interface (and not only through comments or documentation).
std::auto_ptr
: the client will have no doubt that he's transferring ownershipAnyway, going for smart pointers would probably help with these questions.
Upvotes: 3
Reputation: 163318
It should be the responsibility of the caller to manage the memory of objects that are within the caller's scope.
That being said, in this case, you should really use smart pointers because they will deallocate themselves when they are no longer of use.
Upvotes: 2
Reputation: 9657
That's the problem with transferred ownership.
But: You can rewrite your interface to
void obj.setFont( SmartPtr<Font> font );
because then you are forcing the user to use a smart pointer.
Upvotes: 1