I am porting some Java to C++ and rather naively jumped in to using std::vector.
Here is my problem. I have a repository of objects and at some point later I will require
a list of objects from this repository that satisfy some condition. Currently I am reading them into a temporary std::vector. It turns out that when this temporary goes out of scope
it’ll delete its contents and of course that’ll lead to dangling pointers in the repository.
This is my current ‘workaround’, that I find particularly disgusting.
#define NULLIFY(aParam) \
{ \
for (size_t i = 0; i < aParam.size(); i++) { \
aParam[i] = NULL; \
} \
}
typedef std::vector<Object*> TObjectVector;
int main(int argc, char* argv[])
{
PopulateRepository(); // repository uses std::set
TObjectVector subset;
Repository.GetConditionSatisfyingObjects(subset);
DoSomething(subset);
NULLIFY(subset); // Stop destruction of the objects.
}
I’m open to other ideas. I did originally have it all working with raw pointers and dynamic allocation but I wanted to see if there was a speed-up with using STL as I’d have less parameters to pass around. The program is multithreaded and quite CPU intensive.
If you have a vector of pointers such as
std::vector<Object*>, theObjectdestructors will not be called.And if you have a vector of objects, such as
std::vector<Object>, then you store copies of whatever gets “put” in the vector. So I am not sure where the dangling pointers could come from.