handling for references affected by adding elements to std::vector

155 Views Asked by At

As pointed out in answer to another question, all pointers to a vector's elements may become invalid after new elements have been added to that vector, due to reallocation of the underlying contiguous buffer.

Is there a safe way to handle this issue at compile-time?

Are there best-practices to deal with or to avoid a situation, where references may become invalid after altering the data-structure?

2

There are 2 best solutions below

1
On

A pointer or reference to the std::vector itself won't change. What could change is the address of a specific element inside the std::vector due to reallocation policy which is implementation dependent.

Preallocating enough space is a risk because you shouldn't relay on a particular implementation policy.

Storing the address of an element in a std::vector is a bad idea and can be easily avoided because std::vector [] operator is very fast so store the index instead the address of the element. This the right way.

0
On

Are there best-practices to deal with or to avoid a situation, where references may become invalid after altering the data-structure?

  • preallocate enough space for vector in advance
  • keep index of object in array instead of reference/pointer to object itself
  • use different container, for example std::list

which way will work for you the best way depends on your situation