简体   繁体   中英

C++ static members, multiple Objects

I've got some trouble with static members and methods in C++. This is the Class header:

class Decoration {
public:     
    //Static Methods
    static void reloadList();

    //Static Members
    static std::unordered_map<int, Decoration> decorationMapID;
};

And in .cpp:

void Decoration::reloadList() {
    sqlTable result = db->exec("SELECT id, name, description FROM decorations");
    for(sqlRow r: result) {
        Decoration::decorationMapID.insert(std::pair<int,Decoration>(atoi(r[0].c_str()), Decoration(r[1], r[2], atoi(r[0].c_str()))));  
    }
}

Now, in my mainWindow class (I'm using QT5), I call reloadList() and initialize the map. The list is now filled in this Object.

In another Window-Class, I want to use this static list, but the list is empty. Could you explain how I have to use the static members to access the same list everywhere?

Declaration of second class:

in mainWindow.h:

ShoppingLists slDialog;

in mainWindow.cpp I call:

slDialog.setModal(true);  slDialog.show();

Btw.: The whole thing is a CocktailDatabase, so my target is to have a List/Map for Cocktail-, Ingredient-, Decoration-, and Taste- Objects, which I can use without reloading it from SQLite.

You are using the default-constructed value of the static variable before it had a chance to be populated. If you put breakpoints in the code that uses the value and the code that initializes it, you'll see that the latter is called after the former.

1) The static member exists only once and is shared between all the instances of Decoration.

2) The question is why it is empty. Here some hints: a) You think it is empty because some windows object was not refreshed and is not aware that your list was poupulated.
b) Your window get initiaslised before the static list is initialised

3) nevertheless an advice: don't make your static list public , especially if it has to be initialised before it's used. Use a public access function that makes sure it's initialised. Here the rough idea:

class Decoration {
public: 
    std::unordered_map<int, Decoration> getMap(); 

protected:     // or even private ? 
    static void reloadList();
    static bool loaded=false; 
    static std::unordered_map<int, Decoration> decorationMapID;
};

where getMap() would be something like:

if (!loaded) {
    ... // load the list here
     loaded = true; 
}
return (decorationMapID); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM