STL Vector of Unique_ptr - How to reset?

2019-06-22 07:31发布

问题:

I create two standard vector of unique_ptr:

std::vector<std::unique_ptr<Student>> students;
std::vector<std::unique_ptr<Teacher>> teachers;

Then, I create a new object and put it in the vector:

students.push_back(std::unique_ptr<Student> (new Student()));
teachers.push_back(std::unique_ptr<Teacher> (new Teacher()));

After all the operation I have to do, how can I delete the vector?

Whitout unique_ptr I had to do a loop and delete each object:

while (!students.empty())
{
    delete students.back();
    students.pop_back();
}

Now with unique_ptr what have I to do?

I know I have to use unique_ptr::reset (I think).

回答1:

It's simple:

students.clear();

That's what smart pointers (like unique_ptr) are for - they take care of destroying the object pointed to when appropriate.