SFML community forums

Help => General => Topic started by: syndicatedragon on July 26, 2013, 01:16:22 am

Title: Singleton with RenderWindow member and static SFML libs
Post by: syndicatedragon on July 26, 2013, 01:16:22 am
I'm using Visual C++ 2010. The following code crashes when starting a debug session when linked to the SFML static debug libraries. It works FINE debugging when linked to the shared debug SFML libraries! Also, if you comment out the _window member, it works fine with the static libraries. Any ideas why?

#include "SFML\Graphics.hpp"

class Singleton {
protected:
        Singleton() { }
        static Singleton _singleton;
        sf::RenderWindow _window;
};

Singleton Singleton::_singleton;

int main(int argc, char *argv[])
{
    sf::RenderWindow window(sf::VideoMode(200, 200), "SFML works!");
    sf::CircleShape shape(100.f);
    shape.setFillColor(sf::Color::Green);

    while (window.isOpen())
    {
        sf::Event event;
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
                window.close();
        }
        window.clear();
        window.draw(shape);
        window.display();
    }
        return 0;
}
Title: Re: Singleton with RenderWindow member and static SFML libs
Post by: FRex on July 26, 2013, 01:45:46 am
You can't do that, windows can't be global or static or inside globals or statics because of some opengl things that happen behind the scenes.
Title: Re: Singleton with RenderWindow member and static SFML libs
Post by: eXpl0it3r on July 26, 2013, 05:06:21 am
You can't do that, windows can't be global or static or inside globals or statics because of some opengl things that happen behind the scenes.
In theory you can have global variables of it, but the initialization must happen in local space. Since I said theory, I mean theory. In practice you should not be using global variables and since singletons are kinda of the same, you shouldn't use them either. There are enough posts about this on the forum with detailed explanations and discussions for why etc., don't feel like repeating it yet again. :D
Title: Re: Singleton with RenderWindow member and static SFML libs
Post by: syndicatedragon on July 26, 2013, 04:48:55 pm
OK, that's good to know. Honestly I had not seen any indication that it can't be used in this way in the tutorials or documentation.

I'm curious though, why does it work with the dynamic libs?
Title: Re: Singleton with RenderWindow member and static SFML libs
Post by: FRex on July 26, 2013, 07:11:45 pm
Order of initializing globals and statics like that(ie. not in functions, in functions statics are initialized on first function call) is not known at all so sometimes it works and sometimes not.