Your crash problem stems from what I was telling you in the other thread....if you have a vector of pointers, you must take special care!.....if you copy the vector to another, then the new vector recieves copies of the pointers...therefore, to pointers exist for each object on the heap....and if 1 vector calls delete on the object before going out of scope, then the second vector now refers to data that could cause a crash if its dereferenced or deleted!!!!
To get around this, your clone function must implement a deep copy to create more objects on the heap as opposed to copying references to single objects.....
Also, if you are using a clone function, you might want to keep an eye out for the copy constructor and operator=()...they must either do a deep copy too, or be made private and unusable...
Here is the code from the earlier thread.......I altered it a little to show how you can implment the Clone function
Code:
#include <iostream>
#include <string>
#include <vector>
#include <utility>//for std::pair
using namespace std;
class foobar{
typedef vector<pair<string, string>* > MYVECTOR;
typedef MYVECTOR::iterator MYVECTORITER;
foobar(const foobar&);//Make private...rely on foobar::Clone
const foobar& operator=(const foobar&);//Make private...rely on foobar::Clone
MYVECTOR vec;
public:
foobar(){}//Need this as made copy constructor private
void AddPair(const string& lhs,const string& rhs){
pair<string,string>* temp = new pair<string,string>(lhs,rhs);
vec.push_back(temp);
ToScreen();
}
~foobar(){//destructor
for(int i = 0;i < vec.size();++i)
delete vec[i];//delete each
}
void ToScreen(){//Add a print function
MYVECTORITER the_iterator;
for (the_iterator = vec.begin();
the_iterator != vec.end();
++the_iterator){
cout << (*the_iterator)->first << ' ';
cout << (*the_iterator)->second << '\n';
}
}
void Clone(const foobar& rhs){
for(int i = 0;i < vec.size();++i)
delete vec[i];//delete each
vec.clear();//empty current vector
for (int i = 0;i < rhs.vec.size();++i){//Deep copy
pair<string,string>* temp = new pair<string,string>(*rhs.vec[i]);
vec.push_back(temp);
}
}
};
int main(){
foobar f;
f.AddPair("Hello","World");
cout << endl;
f.AddPair("Eat at","Joes");
cout << endl;
f.AddPair("foo","bar");
cout << endl << "From g (cloned from f)" << endl;
foobar g;//make a new foobar
g.Clone(f);//copy f members to g
g.ToScreen();//print out all of g
cout << endl << "From h (cloned from g)" << endl;
foobar h;
h.Clone(g);//Yet another copy
h.ToScreen();
}