开发者

When passing pointers to a class, who should manage the resources?

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 wa开发者_JS百科nt 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


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).

  • In C++03, a good way to make it explicit that you are actually taking ownership is to receive the parameter as a std::auto_ptr : the client will have no doubt that he's transferring ownership
  • On the opposite, receiving a parameter through const reference should make it clear that you have no intention to ever delete the data (you can't possibly know if it has actually been new'ed in the first place).

Anyway, going for smart pointers would probably help with these questions.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜