c ++ - 运行时错误:vector push_back()

时间:2017-06-14 07:55:33

标签: c++ vector runtime push-back

请告诉我此代码有运行时错误的原因。 我认为addEmployee()函数有问题。

#include <iostream>
#include <vector>
#include <string>
using namespace std;

enum EmployeeLevel {fresh, sophomore, junior, senior};

class Employee {
    string name;
    EmployeeLevel level;
public:
    Employee(const string & _name, const EmployeeLevel _level)
        : name(_name) {
        level = _level;
    }
    Employee(const Employee & employee) {
        name = employee.name;
        level = employee.level;
    }
    void changeLevel() {
        level = static_cast<EmployeeLevel> (level + 1);
    }
};

class Manager: public Employee {
    vector<Employee *> group;
public:
    Manager(const string & _name, const EmployeeLevel _level)
        : Employee(_name, _level) {}
    ~Manager() {
        for (vector<Employee *>::iterator it = group.begin(); it != group.end(); ++it)
            delete *it;
    }
    void addEmployee(Employee * employee) {
        group.push_back(employee);
    }
};

int main(void)
{
    Employee e1("홍", fresh), e2("김", sophomore), e3("차", fresh);    

    Manager m1("Tom", senior);
    m1.addEmployee(&e1);
}

如果我修改了函数(addEmployee()),如下所示,而不是错误。 但我想知道为什么使用“push_back(employee)”会出现运行时错误。

void addEmployee(Employee * employee) {
    Employee * tempEmployee = new Employee(*employee);
    group.push_back(tempEmployee);
}

1 个答案:

答案 0 :(得分:0)

第一个版本崩溃的问题是你添加一个指向本地变量的指针,即编译器管理存储的对象。这意味着当Manager被破坏时,它将尝试delete此对象,即您未使用new分配的对象。

只有deletenew(和delete[]new[])的内容!

事实上,我认为没有理由拥有指针。而是有一个普通对象的矢量,即std::vector<Employee>