c++ - How to use multiple pointers to an object by vector/map -


i have question using multiple pointers object. have pointer in vector , 1 in map. map uses vector index object. example code:

class thing { public:     int x = 1; };  thing obj_thing;  std::vector<thing*> v_things;  v_things.push_back(&obj_thing);  std::map<int, thing*> m_thingmap;  m_thingsmap[v_things[0]->x] = v_things[0]; // crucial part 

is practice assign pointers each other this?

should vector and/or map hold addresses instead? or should using pointer pointer map?

it depends on want do.

however, approach can hairy when project grows, , when others contribute it.

to start with, this:

m_thingsmap[v_things[0]->x] = v_things(0); 

should be:

m_thingsmap[v_things[0]->x] = v_things[0]; 

moreover, storing raw pointers in std::vector possible, needs special care, since may end dangling pointers, if object pointer points gets deallocated soon.

for suggest use std::weak_ptr, this:

std::vector<std::weak_ptr<thing>> v_things; 

in case decide stick approach (i mean if pointer points object pointer-shared pointer).


if you, redesign approach, since code not clean enough, let alone logic; takes 1 moment or 2 understand going on pointers , shared places.


Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -