Static Initialization and Ctors

Started by
5 comments, last by SuperVGA 10 years, 9 months ago

Hi guys,

Have been messing with this for a few days now, and now, even though I'm stripping all the code I can, it doesn't seem to change behaviour.

I'm talking about a Segfault that occurs when i try to insert a pair (or anything, really) into a static map, in my constructor.

SceneElement.h :

#ifndef SCENEELEMENT_H
#define SCENEELEMENT_H
 
#include <string>
#include <vector>
#include <map>
 
namespace world
{
    class SceneElement
    {
        protected:
            const std::string name;
const unsigned ssid;
            static unsigned element_ssid_tail;
            
        public:
            static std::map< unsigned, SceneElement* > element_ssid_table;
            static std::map< std::string, SceneElement* > element_name_table;
    
            SceneElement(const std::string &_name = "Unnamed element", const bool _visible = true);
            SceneElement(const SceneElement& orig);
            virtual ~SceneElement();
    };
}
 
#endif /* SCENEELEMENT_H */

SceneElement.cpp :

#include "SceneElement.h"
#include <iostream>
 
namespace world
{
    unsigned SceneElement::element_ssid_tail = 1; // 0 is an invalid subsystem id
    std::map< unsigned, SceneElement* > SceneElement::element_ssid_table = std::map< unsigned, SceneElement* >();
    std::map< std::string, SceneElement* > SceneElement::element_name_table = std::map< std::string, SceneElement* >();
    
    SceneElement :: SceneElement(const std::string &_name, const bool _visible) :
            ssid(SceneElement::element_ssid_tail),
            name(_name)
    {
        ++SceneElement::element_ssid_tail;
        std::cout << this << std::endl; // Outputs reasonable address
        std::cout << &SceneElement::element_ssid_table << std::endl; // Outputs reasonable address
        std::cout << &SceneElement::element_name_table << std::endl; // Outputs reasonable address (located a few bytes after the previous map)
        std::cout << SceneElement::element_ssid_table.size() << std::endl; // Outputs 0
        std::cout << SceneElement::element_ssid_tail << std::endl; // Outputs 2
        
         // Setting the maps here makes everything work. I'd guess that the static map hasn't been initialized properly....
        //SceneElement::element_ssid_table = std::map< unsigned, SceneElement* >();
        //SceneElement::element_name_table = std::map< std::string, SceneElement* >();
        // Crashes!
        SceneElement::element_ssid_table.insert( std::pair< unsigned, SceneElement* >(ssid, this) );
        SceneElement::element_name_table.insert( std::pair< std::string, SceneElement* >(name, this) );
    }
    
    SceneElement :: SceneElement(const SceneElement& orig) :
            ssid(SceneElement::element_ssid_tail),
            name(orig.name)
    {
        ++SceneElement::element_ssid_tail;
        // Crashes!
        SceneElement::element_ssid_table.insert( std::pair< unsigned, SceneElement* >(ssid, this) );
        SceneElement::element_name_table.insert( std::pair< std::string, SceneElement* >(name, this) );
    }
    
    SceneElement::~SceneElement()
    {
        SceneElement::element_ssid_table[ssid] = NULL;
        SceneElement::element_name_table[name] = NULL;
    }
}

The punchline here is, that I've got a GuiElement class that behaves that exact same way, but never crashes.

And I'm not fond of undefined behaviour, so if I'm just being lucky with GuiElement, then I'd rather change it to a "safe" implementation.

I felt confident that everything static, that had been included, compiled and linked would be initialized first thing,

and it looks like the maps have actually been created. Would you give me a hand?

Tips on preventing segfaults are also welcome. I usually create on construction or on the stack, avoid "new" where possible,

and deal in refs instead of pointers, when possible. But this apparently, I have not been able to escape.

Advertisement

Are you creating a SceneElement object, or an object that in turn creates a SceneElement object, statically anywhere? In that case, that object may be constructed before the map constructors, and thus the SceneElement constructor is accessing a not-yet-constructed map object.

Are you creating a SceneElement object, or an object that in turn creates a SceneElement object, statically anywhere? In that case, that object may be constructed before the map constructors, and thus the SceneElement constructor is accessing a not-yet-constructed map object.

For details: http://www.parashift.com/c++-faq/static-init-order.html and http://www.parashift.com/c++-faq/static-init-order-on-first-use.html.

Much like the other mentioned items, I'll just expand and clarify:

C++ only has two levels (to my understanding which is pretty decent) of static initialization. The first level are those static/global items which are pod items. Anything which is a pod item will be initialized to whatever static data is given. So, a pointer for instance, initialized to nullptr is done before any code is run. When it comes to items with complex constructors (your map for instance), there is only one guarantee: items in a "module" (i.e. the same c/cpp file) will initialize in order of appearance. Understanding the actual rules in this is complex and it is easy to find one working case and another non-working case if you didn't understand these rules and abused them. So, you "could" move your user class below the static definition of the map and probably fix things, unless something else outside of the module accesses it and that is completely undefined behavior. sad.png

If you really and absolutely must have the map as a global, wrap it in a function so it is guaranteed to get initialized on the first call. Though "is there really no better way" should always be asked before turning to Singletons. But usually having to do this for every map should be deterrent enough.

map<unsigned, SceneElement*>& someMap()
{
    static map<...> myMap;
    return myMap;
}
f@dzhttp://festini.device-zero.de

Hi guys, I wanted to post a response ~8 hours ago, when GD was having issues, but I'll read Eight and Triencos reply as soon as I get the time.

Are you creating a SceneElement object, or an object that in turn creates a SceneElement object, statically anywhere? In that case, that object may be constructed before the map constructors, and thus the SceneElement constructor is accessing a not-yet-constructed map object.

The first one. (Well, it's within another static function). Actually, I thought I was being clever with omitting that part:
I have a static function in SceneElement called SceneElement* SceneElement::Parse(). It's one of those times where I create on the heap:

    SceneElement* SceneElement::parse(const std::string &source_path, const pugi::xml_node &node)
    {
        bool visible = utility::string_to_bool( node.attribute("visible").as_string("true"), true);
        std::string name = node.attribute("name").as_string("Unnamed element");
        SceneElement* resulting_element = new SceneElement(name, visible);
 
        pugi::xml_node size_child = node.child("size");
        if(!size_child.empty())
        {
        }
 
        pugi::xml_node offset_point_child = node.child("offset_point");
        if(!offset_point_child.empty())
        {
        }
 
        pugi::xml_node offset_child = node.child("offset");
        if(!offset_child.empty())
        {
        }
 
        pugi::xml_node scale_child = node.child("scale"); /* add pixel scaling option/value or granularity value + support for descendance */
        if(!scale_child.empty())
        {
        }
 
        return resulting_element;
    }
This function is called from Grid* Grid::parse(), where Grid : public SceneElement
It behaves in the same way.

Are you creating a SceneElement object, or an object that in turn creates a SceneElement object, statically anywhere? In that case, that object may be constructed before the map constructors, and thus the SceneElement constructor is accessing a not-yet-constructed map object.

For details: http://www.parashift.com/c++-faq/static-init-order-on-first-use.html.

Thanks, Elci. I'll read that now. I've got Cline at al's book, -I love how he describes best practices on parashift. Much appreciated.
Even if it looks like I've done something obviously wrong, I'd really appreciate if you'll further with feedback, in case I just don't get it.
But I'll read the parashift page.... I had no idea that "static initialization order fiasco" was a thing...

Well, that settles it, i guess...

@Trienco, if I absolutely had to do that, I think I'd have made another wrong turn somewhere. I love my project, but not so much that I'm blinded by it,

and I sure will learn from mistakes such as this one. The thing that really scares me though, is if I've unknowingly been practicing something that I thought was good,
but ended up revealing itself as evil much further in the development. I think I'll put the maps elsewhere...

@AllEightUp; thanks for your explanation and your suggestion to move my class below the declaration. But that somehow seems like a hackish way to circumvent the issue.

I do realize that static is evil, but due to how I have been taught, to declare objects and use initialization lists vigorously in constructors, everything seems to be created before i hit main(), and now I see that this is is also a very risky approach (everything is created at once, and it's difficult to control the application-wide order of initialization.)

The maps are something I'm using for addressing the various elements. Each has a unique name and a id unique to the subsystem. I thought it would be nice to make these maps static - the surrounding classes basically only need to read from them. This I will change. I suppose a factory, or my "SceneController" could take care of this.

The ::parse() functions I think, are a OK to keep static within their respective classes.

I should also try to stay away from declaring anything in otherwise global namespaces, as they will be in this pool of objects created before main().

Thanks for all your help. If you have some more input with regards to design, don't hesitate to continue a discussion! I

Good thing I don't have that many units of code now - I can't help imagining my reaction if I had 1000 other classes.
Luckily I only had a few, - but I thought I played safe yet I never saw this coming.

This topic is closed to new replies.

Advertisement