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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With