• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
SuperVGA

Static Initialization and Ctors

6 posts in this topic

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.

Edited by SuperVGA
0

Share this post


Link to post
Share on other sites

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.

1

Share this post


Link to post
Share on other sites

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.

2

Share this post


Link to post
Share on other sites

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

Edited by AllEightUp
1

Share this post


Link to post
Share on other sites

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;
}
2

Share this post


Link to post
Share on other sites

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...
Edited by SuperVGA
0

Share this post


Link to post
Share on other sites

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.

Edited by SuperVGA
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0