SFML community forums

Help => Graphics => Topic started by: svento92 on December 08, 2019, 09:07:19 pm

Title: Following the RAII idiom with textures.
Post by: svento92 on December 08, 2019, 09:07:19 pm
Hi i've recently been reading about some C++ idioms and i'm having a bit of trouble understanding how to follow RAII with for example textures in SFML. My main concern comes from the loadFromFile() function for textures.

Say I want to create a menu with a nice background then(as I understand it) I will first have to instantiate my menu object then load a texture from file. Am I correct in thinking this does not follow RAII? if i'm missing something here I would love some insight.
Title: Re: Following the RAII idiom with textures.
Post by: Laurent on December 09, 2019, 08:15:47 am
It is not clear why you think that "this does not follow RAII", maybe you should explain with more details.

If you imply that sf::Texture should have constructors instead of loadFromXxx functions, then the answer is simple: SFML doesn't use exceptions, so it can't fail in constructors.

And don't forget that the term "RAII" can be misleading, the most important part of it is not resource acquisition but automatic resource cleanup upon destruction.
Title: Re: Following the RAII idiom with textures.
Post by: Hapax on December 10, 2019, 05:47:02 pm
I would suggest that you do all of your loading-from-file for resources (texture or at least images) at or near the beginning (usually) and store them into an "almost global" resource manager. (Definitely) Not actually global but "global enough" so that all graphical entities that use them and also anything that processes them can access them. This could/should include passing stuff around by references or pointers if necessary.

This means that when you create your menu, you already have the textures you need loaded and ready and can be associated as necessary.

Things change when you need to load different textures as things progress (when game level change, for example) but it's mostly the same concept.
Title: Re: Following the RAII idiom with textures.
Post by: Nexus on December 10, 2019, 09:54:35 pm
All SFML classes provide RAII in the sense that they release resources in their destructors.

Textures are no exception. If you call loadFromFile():

Regarding sprites, it is your responsibility to ensure that sprites are outlived by the textures they refer to.