I have 2 classes, say A & B. Class B has a destructor of its own. Within class A, I have a vector of pointers to objects of class B. The vector is as follows:
vector<B*> vect;
In the destructor for class A, how do I retrieve memory? If I cycle through the vector, do I retrieve each object and use delete on every retrieved object? I tried that out in the destructor, but it segfaults.
Any help in solving this problem is most welcome. I am sorry but I cannot post the code.
Some other posts pointed out that you're better of using smart pointers instead of pointers. If you have to use pointer for any reason whatsoever you should delete them in a loop first.
for ( std::vector<B*>::iterator it = vect.begin(); it != vect.end(); ++it)
delete (*it);
vect.clear();
edit: If your program segfault in the destructor then your code is wrong. Maybe you put stack element by adress in the vector, but to delete an object it has to be on the heap.
#include <iostream>
#include <vector>
#include <string>
class data {
public:
std::string d;
data(std::string _d) : d(_d) { }
};
class container {
public:
std::vector<data*> c;
container() { c.clear(); }
void add (data *d) { c.push_back(d); }
~container() {
for (std::vector<data*>::iterator it = c.begin(); it != c.end(); ++it)
delete (*it);
c.clear();
}
};
int main (int argc, char* argv[]) {
typedef std::vector<std::string> sVec;
typedef sVec::iterator sVecIter;
std::vector<std::string> cmd (argv+1, argv+argc);
{
container k;
for (sVecIter it = cmd.begin(); it != cmd.end(); ++it)
k.add(new data((*it)));
}
return 0;
}
This works without problem.