Skip to main content
gamedev.net
🔒 Locked

Static function variable construction timing

Started by JohnBolton Aug 15, 2006 at 5:44 PM 0 replies 1.5k views
Original Post
JohnBolton
JohnBolton
What does the C++ standard say about when a static function variable is considered constructed? I have the following code (broken perhaps, but that's not the point):
    struct foo
    {
        static foo & Instance();
        foo();
        static foo * m_pInstance;
    };
    foo & foo::Instance()
    {
        static foo instance;
        return *m_pInstance;
    }
    foo::foo()
    {
        m_pInstance = this;
        foo::Instance().bar();
    } 
The source of the problem is that Instance() calls the constructor which then calls Instance() again. On two compilers (MSVC 7.1 and another), this causes no problems. The second time Instance() is called, instance is considered constructed and the code continues on. However, on another compiler (GCC 4.0), the second call to Instance() calls the constructor again. Does this fall into the category of "undefined behavior" or are one or more of these compilers broken? Just curious.
John BoltonLocomotive Games (THQ)Current Project: Destroy All Humans (Wii). IN STORES NOW!
SiCrane
SiCrane
According to 6.7 paragraph 4 of the Standard, you're in undefined behavior land.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.