1
Graphics / Re: Sprite doesn't display
« on: May 10, 2025, 01:30:09 am »
This is probably because the texture is after the sprite in your Heart type. It implies the texture is initialized after the sprite, regardless of the texture being before the sprite in Heart constructor's initializer list. So you are initializing the sprite with a texture not yet initialized. The sprite constructor internally queries the texture size, which is an undefined behavior on an uninitialized texture.
To fix it, you could move the texture before the sprite in Heart type.
But even then, storing the texture referenced by the sprite in the same structure is a bad idea. It creates potential lifetime issues.
Consider the following pseudo-code:
In addition, copying the texture in each Heart instance is unnecessary.
You could simply have a single texture instance, which is heart_sprite apparently in your code, and use it to initialize your sprites. This would solve both the initialization order issue and lifetime issue.
To fix it, you could move the texture before the sprite in Heart type.
But even then, storing the texture referenced by the sprite in the same structure is a bad idea. It creates potential lifetime issues.
Consider the following pseudo-code:
Heart h1{player, position}; // h1.sprite references h1.texture
{
Heart h2{player, position};
h1 = h2; // h1.sprite now references h2.texture
} // h2 is destroyed
// h1.sprite references a texture that does not exist anymore -> bug
{
Heart h2{player, position};
h1 = h2; // h1.sprite now references h2.texture
} // h2 is destroyed
// h1.sprite references a texture that does not exist anymore -> bug
In addition, copying the texture in each Heart instance is unnecessary.
You could simply have a single texture instance, which is heart_sprite apparently in your code, and use it to initialize your sprites. This would solve both the initialization order issue and lifetime issue.