jmasterx
jmasterx

Reputation: 54183

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

Answers (3)

icecrime
icecrime

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

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

Upvotes: 3

Jacob Relkin
Jacob Relkin

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

cadolphs
cadolphs

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

Related Questions