删除指针向量 [英] Deleting vector of pointers

查看:109
本文介绍了删除指针向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个类实例的指针,并且程序在编译时不知道我将创建多少个指针. 对于删除,我正在考虑将指针存储在向量中,然后一个一个地删除它们. 使用智能指针会更清洁吗? 而且,如果不想使用智能指针,是否可以将向量的这种使用视为干净的?

I need to create pointers of instances of a class, and the program do not know at compilation time how many pointers I will create. For deletion, I was considering storing the pointers in a vector, and then deleting them one by one. Would the use of smart pointers a cleaner way to go ? And if one does not want to use smart pointers, would this use of vector be considered clean ?

最小代码:

#include <vector>
using namespace std;

class Foo {
public:
    Foo();
};
Foo::Foo(){}
void createFooVector(int nb, std::vector<Foo*> &v){
    for(int i=0;i<nb;i++){
        Foo* f = new Foo();
        v.push_back(f);
    }
}
int main(int argc, char *argv[]){
    std::vector<Foo*> v;
    createFooVector(5,v); 
    while (!v.empty()){
        Foo* f = v.back();
        v.pop_back();
        delete f;
    }
}

推荐答案

我建议使用

I would suggest either using a boost::pointer_vector, an std::vector<std::unique_ptr<Foo>>, or roll out your own Foo manager class which holds a vector<Foo*> and takes care of deletions in the constructor (you should see this as the "expert" solution, and only attempt it if you fully understand exception safety). You don't want to be doing the deletion manually, that can easily lead to errors.

这篇关于删除指针向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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