Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a generic std::vector destructor?

Having a vector containing pointers to objects then using the clear function doesn't call the destructors for the objects in the vector. I made a function to do this manually but I don't know how to make this a generic function for any kind of objects that might be in the vector.

void buttonVectorCleanup(vector<Button *> dVector){
    Button* tmpClass;
    for(int i = 0; i < (int)dVector.size(); i++){
        tmpClass = dVector[i];

        delete tmpClass;
    }
}

This is the function I have that works fine for a specific type of object in the vector but I'd like a single function that could take any kind of vector with object pointers.

like image 509
DShook Avatar asked Dec 03 '22 09:12

DShook


2 Answers

You might want to use boost's pointer containers. They are highly efficient and safe.

like image 100
Leon Timmermans Avatar answered Dec 29 '22 00:12

Leon Timmermans


The best thing to do is use smart pointers, such as from Boost. Then the objects will be deleted automatically.

Or you can make a template function

template <class T>
void vectorCleanup(vector<T *>& dVector){
    T* tmpClass;
    for(vector<T*>::size_type i = 0; i < dVector.size(); i++){
        tmpClass = dVector[i];

        delete tmpClass;
    }

}

like image 42
KeithB Avatar answered Dec 28 '22 23:12

KeithB