the problem is that you have several reference counts floating around for the same object, making it way too easy to destroy the object at the wrong time - you should have one and only one counter for each object. here's a memory manager using reference counts that might be interesting:
and a driver to see how it works:
Code:
#include <string>
#include <vector>
#include <iostream>
#include <pointer>
using namespace std;
using namespace psi;
typedef user <string> base;
typedef memory <string> data;
void print(base & ptr) {
string nil = "(NULL)";
cout << "- " << (ptr ? *ptr : nil) << endl;
}
int main(void) {
vector <data> mst;
mst.push_back(new string("First"));
mst.push_back(new string("Second"));
mst.push_back(new string("Third"));
mst.push_back(new string("Fourth"));
vector <data::user> usr(mst.begin(), mst.end());
cout << "Master List:" << endl;
for_each(mst.begin(), mst.end(), print);
cout << "User List:" << endl;
for_each(usr.begin(), usr.end(), print);
cout << "Erasing first element from master list." << endl;
mst.erase(mst.begin());
cout << "Master List:" << endl;
for_each(mst.begin(), mst.end(), print);
cout << "User List:" << endl;
for_each(usr.begin(), usr.end(), print);
cout << "Erasing NULL data from user list." << endl;
usr.erase(remove(usr.begin(), usr.end(), (string*)NULL), usr.end());
cout << "User List:" << endl;
for_each(usr.begin(), usr.end(), print);
return 0;
}
reference-counting does have a weakness, BTW - the user could possibly mess up the count by calling constructors/destructors manually. in that case you might want to replace the reference counting mechanism with something like an std::set...