C++ static members, multiple Objects

我们两清 提交于 2021-02-11 17:22:06

问题


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.


回答1:


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); 



回答2:


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.



来源:https://stackoverflow.com/questions/24248501/c-static-members-multiple-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!