Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternatives to std::vector due to reallocation that invalidates pointers to elements

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!

like image 525
Adl A Avatar asked Feb 28 '16 14:02

Adl A


1 Answers

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).

like image 53
πάντα ῥεῖ Avatar answered Nov 15 '22 07:11

πάντα ῥεῖ