This is a C++ memory management problem thus I chose to ask here. I am creating a game in SFML. I have used SDL before and managing my Textures was very straightforward but SFML works differently.
My project setup is something like so:
class Game
//create window and initialize game stuff
class Character
/*initializes its own textures and is also responsible for updating itself
as well as drawing itself*/
int main()
/*create an instance of Game -> Create an instance of Character and
runGame. I will implement the drawing and updating properly when I
implement a scene graph and scene nodes but for now updating and drawing is
done via global functions called by the Game Class*/
The challenge I faced was that using an sf::Texture in the Character class for the Sprite image results in a white rectangle being drawn. So the Character Sprite loses its Texture link and SFML just draws a white rectangle. To solve this I created a raw Texture pointer and Initialize it in the Character constructor. This works and the Sprite is drawn correct.
//inside character.hpp
sf::Texture *texture;
//in Character constructor
texture= new (sf::Texture);
This means I have to manage the memory and the code feels ugly.
I have tried this to manage the memory allocated (I think) to prevent a memory leak:
Character::~Character()
{ delete texturePtr; }
but that is wrong obviously. I also tried to delete character.Texture at the end of main() when I exit the application but that causes an error also.
I then tried to do use a uinque_ptr inside the Character constructor:
std::unique_ptr<sf::Texture> texture(new sf::Texture);
//load Texture from Resource Manager instance
and this draws a nice navy blue-black rectangle instead of the Sprite Texture. I am not sure how or if I can declare and then later initialize a unique_ptr.
I think I am leaking memory and if so, how do I correctly use the smart pointers or manage my own memory properly?
I have added a bit more detail and code as I realized I was being vague. Also, I am querying the texture and using it to set the Sprite Rect dimensions so it is definitely being loaded, but just to be safe, I have a logger function that checks if any resource I call is loaded or not.
unique_ptris probably a good idea. If your texture is coming out blue, that sounds like an initialisation bug. Also, consider usingmake_uniqueinstead ofunique_ptr<...> foo(new whatever). - Rook