SFML community forums
Help => Graphics => Topic started by: wademcgillis on August 01, 2009, 05:30:13 pm
-
#include <SFML/Graphics.hpp>
#include <string>
using namespace std;
sf::RenderWindow App;
sf::Sprite load_sprite(string path)
{
sf::Sprite test_sprite;
sf::Image img;
img.LoadFromFile(path);
test_sprite.SetImage(img);
return test_sprite;
}
//#define fromFunction // Un-comment the #define to make the image load incorrectly.
#ifdef _WIN32
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
#else
int main()
#endif
{
App.Create(sf::VideoMode(640, 480, 32), "SFML Window");
sf::Sprite spr;
#ifdef fromFunction
spr = load_sprite("image.bmp");
#else
sf::Image bobf;
bobf.LoadFromFile("image.bmp");
spr.SetImage(bobf);
#endif
spr.SetCenter(120,80);
spr.SetScale(1,1);
spr.SetColor(sf::Color(255,255,255));
spr.SetX(320);
spr.SetY(240);
bool loopin = true;
while(loopin)
{
sf::Event Event;
while (App.GetEvent(Event))
{
if ((Event.Type == sf::Event::Closed) || ((Event.Type == sf::Event::KeyPressed) && (Event.Key.Code == sf::Key::Escape)))
{
App.Close();
loopin = false;
break;
}
}
App.Draw(spr);
App.Display();
sf::Clock clock;
clock.Reset();
while(clock.GetElapsedTime() < 1/60)
{}
}
return EXIT_SUCCESS;
}
Output when fromFunction is defined
(http://i157.photobucket.com/albums/t49/whaddsoft/defined.jpg)
Output when fromFunction is NOT defined
(http://i157.photobucket.com/albums/t49/whaddsoft/notdefined.jpg)
edit:
fixed something. but the problem still occurs
-
The image is deleted at the end of the functions scope.
-
Create a resource manager that has a container and add/remove methods.
-
That's right, it goes out of scope. You need to allocate it with new and return a reference.
-
K-Bal +1
e_barroga +1 ( or use one from the wiki )
Core Xii -1 ( new is not required with a manager so its more easy )
-
Core Xii -1 ( new is not required with a manager so its more easy )
Well... I didn't say it was the easy way. I prefer to do things the right way.
-
Core Xii -1 ( new is not required with a manager so its more easy )
Well... I didn't say it was the easy way. I prefer to do things the right way.
It's not really the right way to create an object in a function and pass a reference to it as the return value. Can lead to dramatic memory leaks because it's a fact a developer *has to know* to use your function properly (very error-prone).
-
The right was would be passing some form of smart pointer. It would fix the problem and memory management would not be an issue.
But, a manager should be looked into for any serious project.
-
You could just create the sprite in your main() function and pass a reference to it as one of the parameters in your Load function. Then you don't even have to worry about memory management or leaks.