STL Vector of Unique_ptr - How to reset?

杀马特。学长 韩版系。学妹 提交于 2019-12-10 14:48:35

问题


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.



来源:https://stackoverflow.com/questions/13652432/stl-vector-of-unique-ptr-how-to-reset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!