C++中的矢量问题

pat*_*ter 1 c++ stl vector

我目前正在开发一个处理People类对象向量的项目.程序编译并运行得很好,但是当我使用调试器时,它在尝试使用PersonWrangler对象时会死掉.我目前有3个不同的课程,一个是人,一个是集体处理所有人的人,一个处理游戏输入和输出的游戏类.

编辑:我的基本问题是理解它在调用outputPeople时死亡的原因.此外,我想了解为什么我的程序完全正常工作,除非我使用调试器.outputPeople函数以我想要的方式工作.

编辑2:callstack有3个错误的调用:

  1. std :: vector> :: begin(this = 0xbaadf00d)
  2. std :: vector> :: size(this = 0xbaadf00d)
  3. PersonWrangler :: outputPeople(此= 0xbaadf00d)

相关代码:

class Game
{
public:
    Game();
    void gameLoop();
    void menu();
    void setStatus(bool inputStatus);
    bool getStatus();
    PersonWrangler* hal;
private:
    bool status;
};
Run Code Online (Sandbox Code Playgroud)

它调用outputPeople,它会立即从baadf00d错误中死掉.

void Game::menu()
{
    hal->outputPeople();
}
Run Code Online (Sandbox Code Playgroud)

其中hal是PersonWrangler类型的对象

class PersonWrangler
{
public:
    PersonWrangler(int inputStartingNum);
    void outputPeople();  
    vector<Person*> peopleVector;
    vector<Person*>::iterator personIterator;  
    int totalPeople;
};
Run Code Online (Sandbox Code Playgroud)

并且outputPeople函数定义为

void PersonWrangler::outputPeople()
{
    int totalConnections = 0;
    cout << " Total People:" << peopleVector.size() << endl;
    for (unsigned int i = 0;i < peopleVector.size();i++)
    {
        sort(peopleVector[i]->connectionsVector.begin(),peopleVector[i]->connectionsVector.end());
        peopleVector[i]->connectionsVector.erase( unique (peopleVector[i]->connectionsVector.begin(),peopleVector[i]->connectionsVector.end()),peopleVector[i]->connectionsVector.end());
        peopleVector[i]->outputPerson();
        totalConnections+=peopleVector[i]->connectionsVector.size();
    }
    cout << "Total connections:" << totalConnections/2 << endl;
}
Run Code Online (Sandbox Code Playgroud)

hal初始化的地方

Game::Game()
{
    PersonWrangler* hal = new PersonWrangler(inputStartingNum);
}
Run Code Online (Sandbox Code Playgroud)

out*_*tis 6

0xBAADFOOD是一个神奇的数字,提醒你你正在处理未初始化的内存.从堆栈跟踪中,我们看到thisin PersonWrangler::outputPeople无效.因此hal,不指向有效PersonWrangler(即,假设第4帧是对其的调用Game::menu).要自己解决这类问题,请逐步完成代码,从开始Game::Game()检查Game::hal,查看可能出现的问题.

Game::Game,hal是一个阴影 的局部变量Game::hal.当Game::Game退出,这hal超出范围和泄漏内存,而Game::hal仍然未初始化.你想要的是:

Game::Game()
{
    hal = new PersonWrangler(inputStartingNum);
}
Run Code Online (Sandbox Code Playgroud)

调试器使用幻数填充未初始化的内存,以便更容易发现错误.在生产构建中,内存中没有任何特定内容; 未初始化的内存的内容是未定义的,并且可能包含有效值.这就是调试构建时生产构建可能不会失败的原因.