SFML community forums

General => Feature requests => Topic started by: danikaze on December 17, 2012, 08:57:27 pm

Title: Texture::Texture explicit
Post by: danikaze on December 17, 2012, 08:57:27 pm
Since it's a expensive resource to load, why not make its constructor explicit to avoid errors.

I was programming a resource manager (which returns a sf::Texture&) and expended about 15 minutes to notice this error:

sf::Texture texture = ResourceManager::getTexture("file.png");
sf::Sprite sprite(texture);
ResourceManager::freeTexture("file.png");

// sprite still displaying even if the Resource Manager texture was freed
 

The reason of the sprite working fine is because sf::Texture has a non-explicit copy constructor. So it was alocating twice the memory required for an image.

The intended behaviour was to free the texture and no image should be displayed

The correct code for this is:

sf::Texture& texture = ResourceManager::getTexture("file.png");
 

I know everything is right, but it would be better if that triggers an error.

If you want to copy a texture still would be possible with the following code:
sf::Texture& texture(ResourceManager::getTexture("file.png"));
 

Same with other expensive resources, as Image, etc.
Title: Re: Texture::Texture explicit
Post by: Nexus on December 17, 2012, 09:25:59 pm
Copy constructors are never explicit. If they were, objects could not be passed to and returned from functions.
Title: Re: Texture::Texture explicit
Post by: danikaze on December 17, 2012, 09:33:19 pm
Copy constructors are never explicit. If they were, objects could not be passed to and returned from functions.

I see.
Any advice to minimize errors about this then? :)
Title: Re: Texture::Texture explicit
Post by: Nexus on December 17, 2012, 11:06:14 pm
Return a pointer instead of a reference ;)
Title: Re: Texture::Texture explicit
Post by: danikaze on December 17, 2012, 11:17:26 pm
Return a pointer instead of a reference ;)
Yeah, that's the other option, but I think returning a reference it's "better", since I can do sprite.setTexture(ResourceManager::getTexture("file.png")) and other things... :P
Title: Re: Texture::Texture explicit
Post by: Laurent on December 17, 2012, 11:22:40 pm
Returning a pointer implies that it can be null, which may not be compatible with your error management policy (for example throwing exceptions).

The only way to avoid unwanted copies in this case is to carefully design and write your code. You will make mistakes at the beginning, but after writing a lot of code you'll automatically avoid this kind of errors.
Title: Re: Texture::Texture explicit
Post by: danikaze on December 17, 2012, 11:30:48 pm
I guess I'll have to stick to the pointer solution, because references need to be initialized when declared, so... pointers it's said.