Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

STL Vector of Unique_ptr - How to reset?

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).

like image 610
LppEdd Avatar asked Nov 30 '12 20:11

LppEdd


1 Answers

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.

like image 63
Angew is no longer proud of SO Avatar answered Oct 19 '22 09:10

Angew is no longer proud of SO