0

I have a static vector of SessionMenu pointers defined in SessionMenu.h as follows:

static vector<SessionMenu *> sessionMenus;

I have defined an accountType enum in the SessionMenu class, and initialise this variable in the constructor of the SessionMenu class.

In the entry point of my application, I add three objects to this vector as follows:

SessionMenu::sessionMenus.push_back(&StudentSessionMenu());
SessionMenu::sessionMenus.push_back(&TutorSessionMenu());
SessionMenu::sessionMenus.push_back(&AdministratorSessionMenu());

At this point, when I debug the SessionMenu::sessionMenus at this point, the pointers are valid and the value of the accountType variable is as expected.

However, later in my application when I iterate over the vector my pointers as so:

for (vector<SessionMenu *>::iterator menuIterator = sessionMenus.begin();
    menuIterator != sessionMenus.end(); ++menuIterator) {
        SessionMenu *currentMenu = *menuIterator;
        if(currentMenu->getAccountType() == accountType)
            return currentMenu;
}

return NULL;

The pointers seem to be pointing somewhere different.

Any ideas what could be causing this?

Cheers.

4

1 回答 1

0

StudentSessionMenu()是暂时的。指针似乎只是有效的,但它们不是。当你检查它们时,记忆已经消失了。你不再拥有它。

奇怪的是,当您尝试获取变量的地址时,您至少不会收到警告。你的警告打开了吗?你无视他们吗?

动态分配对象 ( SessionMenu::sessionMenus.push_back(new StudentSessionMenu());) 或使用智能指针向量。

于 2013-11-07T13:33:59.320 回答