Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting vector of pointers

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 ?

Minimum code:

#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;
    }
}
like image 824
Vince Avatar asked Apr 11 '13 07:04

Vince


People also ask

Do you need to delete a vector of pointers?

Yes, the code has a memory leak unless you delete the pointers. If the foo class owns the pointers, it is its responsibility to delete them. You should do this before clearing the vector, otherwise you lose the handle to the memory you need to de-allocate.

How do I delete a vector pointer?

Another solution is to delete the pointers to remove and set them to nullptr and only then perform a std::remove on nullptr : for(auto& pointer : vec) { if (*pointer % 2 == 0) { delete pointer; pointer = nullptr; } } vec. erase(std::remove(vec.

How do you clear a vector of a pointer in C++?

In short deleting a vector of pointers without creating any memory leaks. delete *it; tckts. erase(tckts.

Does deleting a pointer delete the object?

delete keyword in C++ Pointer to object is not destroyed, value or memory block pointed by pointer is destroyed.


2 Answers

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.

like image 164
juanchopanza Avatar answered Nov 14 '22 23:11

juanchopanza


Your code is fine. However, using smart pointers should be the preferred choice (less code to write and much fewer opportunities for memory bugs).

like image 40
NPE Avatar answered Nov 14 '22 23:11

NPE