STL Vector of Unique_ptr - 如何重置? [英] STL Vector of Unique_ptr - How to reset?

查看:509
本文介绍了STL Vector of Unique_ptr - 如何重置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了两个标准向量的unique_ptr:

  std :: vector< std :: unique_ptr< Student>学生们; 
std :: vector< std :: unique_ptr< Teacher>>教师;然后,我创建一个新对象并将其放入向量:


b

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

完成所有操作后,我如何删除向量?



Whitout unique_ptr我不得不做一个循环并删除每个对象:

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

现在有了unique_ptr我该怎么办?



我知道我必须使用unique_ptr :: reset(我想)。

解决方案

  students.clear(); 

这是智能指针(如 unique_ptr )是为了 - 他们照顾在适当的时候销毁指向的对象。


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.

这篇关于STL Vector of Unique_ptr - 如何重置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆