调用简单的getter方法后出错:basic_string :: _ S_create

时间:2013-11-29 01:12:47

标签: c++ string pointers runtime-error getter

我有一个简单的函数,使用getter方法打印出一个人的名字。它第一次输出的名称很好,但第二次输出错误并停止工作。

调试器显示在初始调用之后,人名的值从应该更改为随机字母和数字的混乱。

非常感谢任何帮助。

error basic_string::_S_create

string personName("Jim");

// check if person already exists (will return NULL in
// the case of Jim during this test)
Person *person = personList.getPerson(personName);

if(!person)
{
    cout << "creating new person" << endl;
    person = createPerson(personName);
    cout << person->getName() << endl; // prints 'Jim'
    cout << person->getName() << endl; // stops working here.
}

Person* createPerson(string name)
{
    Person person(name);
    personList.addPerson(person);
    Person *foundPerson = personList.getPerson(name);
    return foundPerson;
}

PersonList

...

void PersonList::addPerson(Person& person)
{
    Person *person_ptr = &person;
    personList.push_back(person_ptr);
}

Person* PersonList::getPerson(string name)
{
    for(vector<Person*>::iterator it = personList.begin(); it != personList.end(); ++it)
    {
        if((*it)->getName() == name)
        {
            return *it;
        }
    }
}

...

class Person
{
public: 
    Person(string _name)
    string getName() const;
    ...
private:
    string name;
    ...
}

...

Person::Person(string _name)
:name(_name)
{
}

string Person::getName() const
{
    return name;
}

...

1 个答案:

答案 0 :(得分:0)

将您的添加人更改为:

void PersonList::addPerson(Person& person)
{
    Person *person_ptr = new Person(person);
    personList.push_back(person_ptr);
}