STL Vector of Unique_ptr - How to reset?

I create two standard unique_ptr vectors:

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

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

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

After completing the whole operation, how can I remove the vector?

Whitout unique_ptr I had to loop and delete each object:

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

Now with unique_ptr what should I do?

I know that I need to use unique_ptr :: reset (I think).

+4
source share
1 answer

It's simple:

 students.clear(); 

Why smart pointers are needed (for example, unique_ptr ) - they will take care of destroying the object that it points to when necessary.

+13
source

All Articles