this might be a newb question (i am) but i've searched as much as i could to find a solution to the following problem
I have the following scenario (heavily distilled of course):
class Container
{
std::vector<Object> obj;
};
class Pointers
{
std::vector<Object*> obj_ptr;
};
I have a routine that pushes back an element of type Object to the vector obj in Container then pushes back the pointer to that same element to obj_ptr.
the overall idea is that obj_ptr[i] == &obj[i] throughout the life of the program.
The problem I run into is that whenever the capacity of obj needs to increase all the pointers are invalidated, making the obj_ptr completely useless. I have tried both obj.reserve() using the maximum expected size (around 10^7) and initializing the vector with that same size. Problem still persists.
Not sure if it's important, but I'm using VS 2015 Com.
Thanks!
The common alternative is using smart pointers like
class Container {
std::vector<std::unique_ptr<Object>> obj;
};
or
class Container {
std::vector<std::shared_ptr<Object>> obj;
};
Depends on your use case (semantically).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With